排列多个图并使用一个图例和一个x轴标题

时间:2018-08-22 13:06:25

标签: r ggplot2

我在四个位置测量了两种重金属的重金属浓度,并具有以下数据集:

library(data.table)
library(ggplot2)
library(gridExtra)

Date <- c("2013-01-01","2013-01-10","2013-01-16","2013-01-19")
conc1<-c("1.5","2.5","1.5","3.5")
conc2<-c("2","3","4","3")
y1 <- data.frame(Date,conc1,conc2)
y1$Date <- as.Date(y1$Date)
y1_melt<-melt(y1, id=c("Date"))
y1_melt$value<-as.numeric(y1_melt$value)

Date <- c("2013-01-01","2013-01-10","2013-01-16","2013-01-19")
conc3<-c("1.5","2.5","1.5","3.5")
conc4<-c("2","3","4","3")
y2 <- data.frame(Date,conc3,conc4)
y2$Date <- as.Date(y2$Date)
y2_melt<-melt(y2, id=c("Date"))
y2_melt$value<-as.numeric(y2_melt$value)

Date <- c("2013-01-01","2013-01-10","2013-01-16","2013-01-19")
conc5<-c("1.5","2.5","1.5","3.5")
conc6<-c("2","3","4","3")
y3 <- data.frame(Date,conc5,conc6)
y3$Date <- as.Date(y3$Date)
y3_melt<-melt(y3, id=c("Date"))
y3_melt$value<-as.numeric(y3_melt$value)

Date <- c("2013-01-01","2013-01-10","2013-01-16","2013-01-19")
conc7<-c("1.5","2.5","1.5","3.5")
conc8<-c("2","3","4","3")
y4 <- data.frame(Date,conc7,conc8)
y4$Date <- as.Date(y4$Date)
y4_melt<-melt(y4, id=c("Date"))
y4_melt$value<-as.numeric(y4_melt$value)

我创建了四个单独的图,每个位置一个图:

p1<-ggplot(y1_melt, aes(x=Date, y=value, colour=variable))+geom_line()
p2<-ggplot(y2_melt, aes(x=Date, y=value, colour=variable))+geom_line()    
p3<-ggplot(y3_melt, aes(x=Date, y=value, colour=variable))+geom_line()
p4<-ggplot(y4_melt, aes(x=Date, y=value, colour=variable))+geom_line()

我想要一个包含4个图的组合图,共享一个图例。因此,我提取了图例:

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

我创建了一张图:

p5 <- grid.arrange(arrangeGrob(p1 + theme(legend.position="none"),
                           p2 + theme(legend.position="none"),
                           p3 + theme(legend.position="none"),
                           p4 + theme(legend.position="none"),
                           nrow=2),
               mylegend, nrow=2,heights=c(50,10))
p5

但是,我想将图例放在组合图的下方,并且我希望在任一侧都只有一个x轴,因为左侧和右侧的两个图都具有相同的x轴

0 个答案:

没有答案