2017-08-14 46 views
4

我一直要求重新使用ggplot2饼图时遇到困难,增加第二个标题的情节极坐标。我需要的情节右下角左下角的标题。第二字幕添加到基于GGPLOT2情节

我目前的做法能得到一个或另一个通过使用用于字幕的展示位置(左对齐0;为右对齐1)hjust选项:

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) 

这产生:

Pie chart with right caption

我见过一些使用annotate()的方法,但我似乎无法让它们与coord_polar()一起使用。

有谁知道我怎样才能得到一个第二标题出现在情节的左侧(水平与右对齐标题)?也许有可能覆盖只有左标题的空白图层?

+0

我绝对不是在使用哈克解决方案,但我希望有一种方法可以做到这一点是重复性更好一点。该解决方案将需要大量的试验和错误的用空格数左,右字幕,并根据情节是如何保存/导出,该值可能会改变之间包括。 –

回答

3

使用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

+0

非常酷!只是为了更好地理解这一点:在这种情况下,addGrobs()为标题列表添加一个新的子元素?快速浏览一下,我原本以为它会覆盖位于'p2 $ grobs [[k]]'中的东西。 –

+1

@Twitch_City是,'addGrobs'增加了一个新的孩子标题GROB(一个'gTree')。我们不能覆盖'p2 $ grobs [[k]]',否则我们会丢失正确的(子)标题。 –