[英]Add second caption to polar coordinates based ggplot2 plot
我被要求使用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()
。
有谁知道我怎么能在图的左侧出现第二个标题(与右侧标题水平对齐)? 也许可以覆盖只有左标题的空白图层?
使用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.