使用ggplot2绘制多图

3
我正在使用ggplot2进行多图绘制。尽管经过了很多调整,我仍然面临以下问题:
  1. 每个图的左/右两侧都会绘制出一些空白区域。我在每个图的右侧标记了这一点。
  2. 图形没有通过左侧对齐。这个问题在底部的图中明显。
  3. Y轴标签距离图形太远。我能减少这个间隔吗?

多图如下:

enter image description here

我使用了以下R代码:

p1 <- ggplot(data = dplots[[1]],aes(timestamp,power/1000))+ geom_line()+
      ylab("")+theme(axis.text.x=element_blank(),axis.title.x=element_blank(),axis.ticks.x=element_blank(),plot.margin = unit(c(-0.3,1,-0.3,1), "cm"))+labs(title="room1")
p2 <- ggplot(data = dplots[[2]],aes(timestamp,power/1000))+ geom_line()+
  ylab("")+theme(axis.text.x=element_blank(),axis.title.x=element_blank(),axis.ticks.x=element_blank(),plot.margin = unit(c(-0.3,1,-0.3,1), "cm"))+ labs(title="room2")
p3 <- ggplot(data = dplots[[6]],aes(timestamp,power/1000))+ geom_line()+
  ylab("")+theme(axis.text.x=element_blank(),axis.title.x=element_blank(),axis.ticks.x=element_blank(),plot.margin = unit(c(-0.3,1,-0.3,1), "cm"))+ labs(title="room3")                      
p4 <- ggplot(data = dplots[[4]],aes(timestamp,power/1000))+ geom_line()+
  ylab("")+theme(axis.text.x=element_blank(),axis.title.x=element_blank(),axis.ticks.x=element_blank(),plot.margin = unit(c(-0.3,1,-0.3,1), "cm"))+ labs(title="room4")
p5 <- ggplot(data = dplots[[5]],aes(timestamp,power/1000))+ geom_line()+
  ylab("")+theme(axis.text.x=element_blank(),axis.title.x=element_blank(),axis.ticks.x=element_blank(),plot.margin = unit(c(-0.3,1,-0.3,1), "cm"))+ labs(title="room5")
p6 <- ggplot(data = dplots[[3]],aes(timestamp,power/1000))+ geom_line()+
        ylab("")+theme(axis.title.x=element_blank(),axis.ticks.x=element_blank(),plot.margin = unit(c(-0.3,1,-0.3,1), "cm"))+ labs(title="Chiller") +
       scale_x_datetime(labels= date_format("%d-%m-%y",tz ="UTC"),breaks = pretty_breaks(8)) 
grid.arrange(p1,p2,p3,p4,p5,p6,nrow=6,ncol=1,heights=c(0.15,0.15,0.15,0.15,0.15,0.15),left="Power (KW)")  

数据集(dplots)存储在链接中。

2
尝试查看这个(对齐图表)这个(保持比例) - JasonAizkalns
3
我是否遗漏了不使用facet的理由? - Akhil Nair
2个回答

10

最简单的解决方案可能是将列表中的数据框合并为一个数据集。使用data.table包中的rbindlist函数,您还可以为每个数据框包含id:

library(data.table)
# bind the dataframes together into one datatable (which is an enhanced dataframe)
DT <- rbindlist(dplots, idcol = "id")
# give names to the id's
DT$id <- factor(DT$id, labels = c("room 1","room 2","room 3", "room 4","room 5","Chiller"))

library(ggplot2)
ggplot(DT, aes(x = timestamp, y = power)) + 
  geom_line() + 
  scale_x_datetime(expand = c(0,0)) +
  facet_grid(id ~ ., scales="free_y") +
  theme_bw()

这将导致以下图表:

enter image description here


5
使用现有的代码,可以使用cowplot包:
library(cowplot)
plot_grid(p1,p2,p3,p4,p5,p6,ncol=1,align = "v")

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接