r - Add second caption to polar coordinates based ggplot2 plot -
i have been asked recreate pie chart using ggplot2
, having difficulty adding second caption plot. need caption on bottom left of plot and bottom right.
my current approach can 1 or other using hjust
option caption placement (0 left-align; 1 right-align):
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 approaches use annotate()
cannot seem them work coord_polar()
.
does know how can second caption appear on left-hand side of plot (horizontally aligned right caption)? maybe possible overlay blank layer has left caption?
using grid
package possible add text grob containing left caption.
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 ggplot2 plot grob p2 <- ggplotgrob(p1) # find grob tree containing right caption (as child) k <- which(p2$layout$name=="caption") # copy "right caption" text grob in grbtxt grbtxt <- p2$grobs[[k]]$children[[1]] # modify content , position of 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) title grob containing right caption p2$grobs[[k]] <- addgrob(p2$grobs[[k]],grbtxt) grid.draw(p2)
Comments
Post a Comment