在基于ggplot2的极坐标图中添加第二个标题

6

我被要求使用ggplot2重新创建一个饼图,但是在向图表添加第二个标题时遇到了困难。我需要在图表的左下角和右下角分别添加标题。

我当前的方法可以通过使用hjust选项来获得其中之一的标题位置(0表示左对齐;1表示右对齐):

library(ggplot2)
dat <- data.frame(variable = c("V1", "V2", "V3"),
                  value = c(.80,.50,.63))
p1 <- ggplot(dat, 
             aes(x = 1, y = value, fill = variable)) +
  geom_bar(stat = "identity") +
  coord_polar(theta = "y")  +
  theme(legend.position = 'none',
        plot.caption = element_text(hjust = 1)) +
  labs(caption  = "RIGHT CAPTION")

print(p1)

这将产生以下结果:

带右标题的饼图

我看到一些方法使用annotate(),但我似乎无法与coord_polar()一起使用。
有人知道如何在绘图的左侧出现第二个标题(与右标题水平对齐)吗?也许可以叠加一个只有左标题的空白层?

我绝对不排斥使用hacky的解决方案,但我希望有一种更可复制的方法来解决这个问题。这种解决方案需要大量的试错,在左右字幕之间包括多少空格取决于图形保存/导出的方式,该值可能会发生变化。 - Twitch_City
1个回答

5
使用grid包,可以添加一个包含左侧标题的文本grob。
library(ggplot2)
library(grid)
dat <- data.frame(variable=c("V1", "V2", "V3"), value=c(.80,.50,.63))

p1 <- ggplot(dat, aes(x = 1, y = value, fill = variable)) +
  geom_bar(stat = "identity") +
  coord_polar(theta = "y") +
  theme(legend.position='none', plot.caption=element_text(hjust=1)) +
  labs(caption="RIGHT CAPTION")

# Generate a ggplot2 plot grob
p2 <- ggplotGrob(p1)
# Find the grob tree containing the right caption (as child)
k <- which(p2$layout$name=="caption")
# Copy the "right caption" text grob in grbTxt
grbTxt <- p2$grobs[[k]]$children[[1]]

# Modify content and position of the text grob  
grbTxt$label <- "LEFT CAPTION"
grbTxt$name <- "GRID.text.left"
grbTxt$x <- unit(0,"npc")
grbTxt$hjust <- 0
grbTxt$gp$col <- "red"

# Add grbTxt (left caption) to the title grob containing the right caption
p2$grobs[[k]] <- addGrob(p2$grobs[[k]],grbTxt)
grid.draw(p2)

enter image description here


非常酷!只是为了更好地理解这一点:在这种情况下,addGrobs()会将一个新的子项添加到标题列表中吗?快速看一下,我一开始认为它会覆盖p2$grobs[[k]]中的内容。 - Twitch_City
1
@Twitch_City 是的,addGrobs 会向标题 grob(即 gTree)添加一个新的子项。我们不能覆盖 p2$grobs[[k]],否则就会失去正确的(子项)标题。 - Marco Sandri

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接