【问题标题】:Adding legend for list of ggplots created in loop为循环中创建的 ggplots 列表添加图例
【发布时间】:2017-07-19 09:05:46
【问题描述】:

我正在使用 ggplot2 中的循环创建一个绘图列表(没有图例)。然后我分别创建了一个图例并尝试使用 grid.arrange 和 grobs 函数打印组合图。它创建了组合图,但没有图例。谁能帮忙解决这个问题?

我在这里附上我的代码:

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

【问题讨论】:

    标签: r loops ggplot2 legend


    【解决方案1】:
    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-06
      • 1970-01-01
      • 1970-01-01
      • 2020-09-09
      相关资源
      最近更新 更多