[英]Add second caption to polar coordinates based ggplot2 plot
I have been asked to recreate a pie chart using ggplot2
and am having difficulty adding a second caption to the plot. 我被要求使用
ggplot2
重新创建一个饼图,并且很难在图中添加第二个标题。 I need a caption on the bottom left of the plot and the bottom right. 我需要在情节的左下角和右下角有一个标题。
My current approach can get one or the other by using the hjust
option for the caption placement (0 for left-align; 1 for right-align): 我目前的方法可以通过使用标题放置的
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)
This produces: 这会产生:
I've seen some approaches that use annotate()
but I cannot seem to get them to work with coord_polar()
. 我已经看到一些使用
annotate()
方法,但我似乎无法让它们与coord_polar()
。
Does anyone know how I can get a second caption to appear on the left-hand side of the plot (horizontally aligned with the right caption)? 有谁知道我怎么能在图的左侧出现第二个标题(与右侧标题水平对齐)? Maybe it is possible to overlay a blank layer that only has a left caption?
也许可以覆盖只有左标题的空白图层?
Using the grid
package it is possible to add a text grob containing the left caption. 使用
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.