2017-07-31 39 views
0

我不知道如何將標籤leftright一邊放在facet_grid條的一側。在facet_grid的條紋外面放置標籤

作爲一個重複的例子,我想先從這個例子

library(ggplot2) 
    ggplot(mtcars, aes("", hp)) + 
     geom_boxplot(width=0.7, position=position_dodge(0.7)) + 
     theme_bw() + 
     facet_grid(. ~ vs + am + carb,switch = 'both',labeller = label_both) + 
     theme(panel.spacing=unit(0.2,"lines"), 
      strip.background=element_rect(color="grey30", fill="grey90"), 
      panel.border=element_rect(color="grey90"), 
      axis.ticks.x=element_blank())+ 
      #strip.placement="outside") + 
     labs(x="") 

enter image description here

我找的情節;

enter image description here

+1

不要以爲可以做到的 「直接」。試着在第二個圖表中繪製圖形,然後調用類似'grid.text(「vs」,x = 0.98,y = 0.1)',儘管你必須擺弄數字以準確地將它放在需要的地方。 –

+1

例如https://stackoverflow.com/a/29594608/2706826 –

回答

3

可以隨時標題手動添加到gtable,

enter image description here

g <- ggplotGrob(p) 

library(gtable) 
library(grid) 
library(gridExtra) 
pos <- subset(g$layout, grepl("strip",name)) 
titles <- tableGrob(c("vs","am","carb"), theme = ttheme_minimal(9)) 
titles$heights <- unit(rep(1,3), "null") 
g$widths[ncol(g)] <- sum(titles$widths) 
g <- gtable_add_grob(g, titles, t=unique(pos$t), l = ncol(g)) 
grid.newpage() 
grid.draw(g) 
+0

感謝您的答案。其實我正在尋找這樣的答案,因爲我也試圖將常見條合併爲一個共同的條,如[這個問題](https://stackoverflow.com/questions/40732543/seeking-workaround-for-gtable-add -grob-code-broken-by-ggplot-2-2-0)。是可以將這些行添加到'OverlappingStripLabels'? – Alexander

+0

作爲'pos'將有兩個不同的定義。 – Alexander

+0

嗨@baptiste你能看到我最後的評論嗎?我嘗試了一些,但仍然無法將您的解決方案合併到'OverlappingStripLabels()'中 – Alexander

相關問題