2017-03-03 85 views
0

我用marrangeGrob()而不是facet_wrap()從圖表列表中生成我的圖。但是,我似乎無法添加圖例。marrangeGrob,但不能添加傳說

我已經提取使用

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)} 

但是我的傳說,我無法添加它是我的陰謀。 有沒有人知道一種方式?

+0

好了,我們需要看到你正在運行的代碼,最好用,讓我們重新創建的情節和傳說中的樣本數據,看什麼地方出了錯。例如,如果你有兩個圖,'p1'和'p2',並且你在一個名爲'leg'的對象中存在這個圖例,那麼例如'marrangeGrob(p1,p2,leg,widths = c(5,5 ,1))'應該工作。 – eipi10

+0

嗯,它更像是我有一個名爲leg和plot1 <-marrangeGrob(list_of_plots,ncol = 4,nrow = 5)的grob。我想把這個圖例添加到我從這個 –

+0

產生的pdf中。'g_legend'函數返回圖例的grob。您需要在撥打'marrangeGrob'時加入這個grob。如果您提供可重複的示例,我可以提供代碼。 – eipi10

回答

0

下面是一個使用內置diamonds數據幀的例子:

library(ggplot2) 
library(gridExtra) 
library(dplyr) 

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)} 

首先,我們將創建兩個地塊一同鋪陳:

df <- count(diamonds, cut) 

p1 = ggplot(df, aes(x=cut, y=n, label=format(n, big.mark=","), fill=cut)) + 
    geom_bar(stat="identity") + 
    geom_text(aes(y=0.5*n), colour="white") + 
    coord_flip() + 
    theme(legend.position="bottom") 

p2 = ggplot(diamonds %>% sample_n(1000), aes(x=carat, y=price, colour=cut)) + 
    geom_point() 

現在從p1保存傳說爲單獨的grob:

leg = g_legend(p1) 

將兩個圖並排放置u唱歌arrangeGrob,然後使用marrangeGrob佈置雙小區佈局和它下面的圖例。請注意,我們也從原始圖中刪除了圖例。

marrangeGrob(grobs=list(
    arrangeGrob(grobs=lapply(list(p1,p2), function(p) { 
    p + guides(colour=FALSE, fill=FALSE) 
    }), ncol=2), 
    leg), ncol=1, nrow=2, heights=c(20,1)) 

enter image description here

+0

在我的情況下,我的數據框並沒有使用p1和p2,而是在一個列表中。 list_df = [df1],[df2],....我用lapply(list_df,ggplot)創建ggplots列表。您的解決方案是否仍然適用於此? –

+0

抱歉,不得不編輯我的評論。 –

+0

我的解決方案使用ggplots('list(p1,p2)')列表。在你的情況下,列表是'plot_list = lapply(list_df,ggplot)'或者你爲了創建你的圖表而做的任何事情。 – eipi10