简体   繁体   English

为循环创建的ggplots列表添加图例

[英]Adding legend for list of ggplots created in loop

I am creating a list of plots (without legend) by using a loop in ggplot2. 我通过使用ggplot2中的循环创建了一个绘图列表(没有图例)。 Then I created a legend separately and trying to print a combined plots by using grid.arrange and grobs function. 然后,我分别创建了一个图例,并尝试使用grid.arrange和grobs函数打印组合图。 It creates the combined plot but without the legend. 它创建组合图,但没有图例。 Could anyone please help to solve the problem? 任何人都可以帮助解决问题吗?

I am attaching my code here: 我在这里附上我的代码:

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()
grid.arrange(grobs=c(plot.list,list(legend)), 
             ncol=1, heights = c(2,2,2,0.35))

or simply 或简单地

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM