2017-08-14 45 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]]',否則我們會丟失正確的(子)標題。 –