2017-07-19 21 views
1

我正在使用ggplot2中的循環創建圖表列表(無圖例)。然後我分別創建了一個圖例,並嘗試使用grid.arrange和grobs函數來打印組合圖。它創建組合情節,但沒有傳說。任何人都可以請幫忙解決這個問題嗎?爲循環中創建的ggplots列表添加圖例

我在這裏附上我的代碼:

df1<-data.frame(x=1:10,y1=rnorm(10),y2=rnorm(10),y3=rnorm(10),y4=rnorm(10),y5=rnorm(10)) 
df2 <- melt(df1,id.vars="x") 

plot.list = list() 

for (i in 1:3){ 
    p <- ggplot(df2, aes(x=x, y=value)) + 
    geom_line(aes(colour=variable, group=variable))+ 
    theme(legend.position='none') 
    plot.list[[i]] = p 
} 

temp_legend <- ggplot(df2, aes(x=x, y=value)) + 
    geom_line(aes(colour=variable, group=variable)) + 
    scale_color_manual("",labels = c("Observed","3d","5d","7d","10d"), values = c("black", "limegreen","blue","tan1","red3")) + 
    theme(legend.direction = "horizontal", 
     legend.position = "bottom") 

library(gridExtra) 
# create get_legend function 
get_legend<-function(myggplot){ 
    tmp <- ggplot_gtable(ggplot_build(myggplot)) 
    leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box") 
    legend <- tmp$grobs[[leg]] 
    return(legend) 
} 

# Extract legend using get_legend function 
legend <- get_legend(temp_legend) 

# png export 
png("Output.png", width = 5, height = 6.35, units = 'in', res = 300) 
grid.arrange(grobs=plot.list,legend, 
      ncol=1, nrow = 4, 
      widths = 6, heights = c(2,2,2,0.35)) 
dev.off() 

回答

2
grid.arrange(grobs=c(plot.list,list(legend)), 
      ncol=1, heights = c(2,2,2,0.35)) 

或者乾脆

grid.arrange(grobs=plot.list, ncol=1, bottom = legend)