2015-04-22 115 views
1

我有一個圖形做分類變量的條形圖(例如組A,組B,...)。我想在一個頁面上有多個圖表(類似this)。我想用創建情節之外的文本:ggplot2位置annotation_custom外面的多個圖形在一個頁面上

###### Plot three graphs together with one legend and one text on the right side 

## this is the function that make one legend for multiple graphs 
g_legend <- function(a.gplot){ 
    tmp <- ggplot_gtable(ggplot_build(a.gplot)) 
    leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box") 
    legend <- tmp$grobs[[leg]] 
    return(legend)} 

mylegend <- g_legend(p3.legend) 

### combine three graphs with legend  
p <- grid.arrange(arrangeGrob(p1 , p2 , p3, mylegend, ncol = 4, widths = c(20, 20, 20, 11))) ## vertical 

### create text to put outside this multi-graph plot 
Text1 = textGrob(paste("An example text"))  
p1 = p + annotation_custom(grob = Text1, xmin = 1, xmax = 2, ymin = 20, ymax = 30) 

它給了我「非數字的參數,以二進制運算錯誤」的錯誤。由於x軸是分類變量,所以我認爲錯誤是由xmax引起的,所以xmin值不能分配給分類數據。所以我用p1 = p + annotation_custom(grob = Text1,xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf)。再次這個相同的錯誤。

我知道如何在此基礎上參考了多圖情節外辦傳說: ggplot2: multiple plots with different variables in a single row, single grouping legend

的例子以外的Displaying text below the plot generated by ggplot2文字是有幫助的。但是這是一個圖表,我不覺得它在我的多圖情節中很有用。

任何關於錯誤原因的想法,或者如何爲具有分類x/y變量的多頁圖表定位註釋?

回答

0

就像這樣,你在x軸上有一個因子變量,並使用因子整數來定位文本grob?

require(ggplot2) 
df <- data.frame(a = seq(0, 30, 6), group = as.factor(c("a", "b", "c", "d", "e", "f"))) 

Text1 <- textGrob("Test text") 
ggplot(data = df, aes(x = group, y = a)) + 
    geom_bar(stat = "identity") + 
    annotation_custom(grob = Text1, xmin = 2, xmax = 3, ymin = 20, ymax = 22) 

enter image description here

+0

enaJ,你想把文本作爲一個整體放在圖上,就像所有圖的標題一樣嗎?你能否向你的問題添加一些可重現的數據和創建圖的代碼,觸發錯誤的代碼? – lawyeR

+0

我希望文字在右側作爲註釋,而不是標題。我按照你的建議編輯了我的問題。 – enaJ