如何使网格中的所有图都布置为相同大小。一些在轴上带有标签,而其他都没有?

时间:2018-12-12 17:57:32

标签: r ggplot2

我要在同一图中显示4个图。我可以用ggplot2和grid.arrange做到这一点。但是,为了使其更整洁,我想删除一些多余的标签和轴值,因为从本质上讲,它是同一图重复4次。

这是我的原始代码:

x <- 1:100
y1 <- sample(x = c(1,2, 3, 4, 5, 6, 7, 8, 9, 10), size = 100, replace =  TRUE)
y2 <- sample(x = c(1,2, 3, 4, 5, 6, 7, 8, 9, 10), size = 100, replace = TRUE)
y3 <- sample(x = c(1,2, 3, 4, 5, 6, 7, 8, 9, 10), size = 100, replace = TRUE)
y4 <- sample(x = c(1,2, 3, 4, 5, 6, 7, 8, 9, 10), size = 100, replace = TRUE)

df <- data.frame(x, y1, y2, y3, y4)

library(ggplot2)
library(grid)
library(gridExtra)

#Create 4 simple plots 
plot1 <- ggplot(df, aes(x = x, y = y1)) + geom_line() +
labs(y = "Temperature") +  labs(x = "Hours") +  labs(title = "Y1") +
theme_bw()
plot(plot1)

plot2 <- ggplot(df, aes(x = x, y = y2)) + geom_line() +
labs(y = "Temperature") +  labs(x = "Hours") +  labs(title = "Y2") +
theme_bw()
plot(plot2)

plot3 <- ggplot(df, aes(x = x, y = y3)) + geom_line() +
labs(y = "Temperature") +   labs(x = "Hours") +  labs(title = "Y3") +
theme_bw()
plot(plot3)

plot4 <- ggplot(df, aes(x = x, y = y4)) + geom_line() +
labs(y = "Temperature") +  labs(x = "Hours") +  labs(title = "Y4") +
theme_bw()
plot(plot4)

# combine plots
All_plot <- grid.arrange(plot1, plot2, plot3, plot4, ncol = 2)

enter image description here

这些是原始图,看起来不错,但我想删除Y1和Y2的x轴以及Y2和Y4的Y轴。

我在ggplot中这样做:

plot1 <- ggplot(df, aes(x = x, y = y1)) + geom_line() +
  labs(y = "Temperature") +  labs(title = "Y1") +
  theme_bw() +
  theme(axis.title.x=element_blank(), axis.text.x=element_blank(),axis.ticks.x=element_blank()) 
  plot(plot1)

plot2 <- ggplot(df, aes(x = x, y = y2)) + geom_line() +
  labs(title = "Y2") +
  theme_bw() +
  theme(axis.title.x=element_blank(), axis.text.x=element_blank(),axis.ticks.x=element_blank()) +
  theme(axis.title.y=element_blank(), axis.text.y=element_blank(),axis.ticks.y=element_blank())
 plot(plot2)

 plot3 <- ggplot(df, aes(x = x, y = y3)) + geom_line() +
  labs(y = "Temperature") +   labs(x = "Hours") +  labs(title = "Y3") +
  theme_bw()
 plot(plot3)

 plot4 <- ggplot(df, aes(x = x, y = y4)) + geom_line() +
   labs(x = "Hours") +  labs(title = "Y4") +
   theme_bw() +
   theme(axis.title.y=element_blank(), axis.text.y=element_blank(),axis.ticks.y=element_blank())
plot(plot4)

All_plot <- grid.arrange(plot1, plot2, plot3, plot4, ncol = 2)

enter image description here

但是地块大小不同吗? Y1和Y2较高,Y2和Y4较宽。如何使方形框的尺寸都相同?

2 个答案:

答案 0 :(得分:1)

尝试Edit库:

https://github.com/thomasp85/patchwork

patchwork

这是一个神奇的图书馆.....玩得开心

答案 1 :(得分:0)

我建议使用Y1,Y2等进行构面。为此,您必须先gather y。

library(tidyverse)

df %>% 
  #gather the y's to a new column named Variable
  gather(contains('y'), key = Variable, value = Value) %>% 
  ggplot(aes(x, Value)) + 
  geom_line() + 
  #facet by Variable
  facet_wrap(~ Variable) + 
  theme_bw()

enter image description here