在ggplots上定义相等的边距/大小

时间:2018-05-27 18:44:29

标签: r ggplot2

我有这两个代码:

v <- melt(tvalB)
data1 <- as.data.frame(cbind(tval, v$value))
sizez <- 14
ggplot(data = data1, aes(x =T-value)) +
  geom_density(aes(tval, fill = "Actual"), alpha = 0.5, adjust=8) +
  geom_density(aes(V2, fill = "Simulation"), alpha = 0.5, adjust=8) +
  scale_colour_manual("", breaks = c("Actual", "Simulation"),
                  values = c("red", "blue")) +
  scale_y_continuous("density") + 
  scale_x_continuous("t(alpha)", limits = c(-6.5,6.5)) +
  labs(title ="") +
  theme(plot.title = element_text(hjust = 0.5)) +
  guides(fill=guide_legend(title=NULL)) + 
  theme(legend.title=element_text(size=sizez+1),legend.text=element_text(size=sizez),
    axis.text=element_text(size=sizez-1), axis.title=element_text(size=sizez), 
    legend.key = element_rect(size = 0.05),
    legend.key.height = unit(1.25, "cm"),
    legend.key.width = unit(1.25, "cm"))

data1 %>% 
  gather(key, value) %>% 
  ggplot(aes(value, color=key)) + 
  stat_ecdf(size=0.8)+ xlim(-4.5,4.5) + 
  labs(x = "t(alpha)", y = "probability", color=NULL) + 
  scale_colour_discrete(labels = c("Actual","Simulation")) + 
  theme(legend.title=element_text(size=sizez+1), legend.text=element_text(size=sizez),
    axis.text=element_text(size=sizez-1), axis.title=element_text(size=sizez), 
    legend.key = element_rect(size = 4),
    legend.key.height = unit(1.3, "cm"),
    legend.key.width = unit(1.3, "cm"))data1 %>% 
  gather(key, value) %>% 
  ggplot(aes(value, color=key)) + 
  stat_ecdf(size=0.8)+ xlim(-4.5,4.5) + 
  labs(x = "t(alpha)", y = "probability", color=NULL) + 
  scale_colour_discrete(labels = c("Actual","Simulation")) + 
  theme(legend.title=element_text(size=sizez+1), legend.text=element_text(size=sizez),
    axis.text=element_text(size=sizez-1), axis.title=element_text(size=sizez), 
    legend.key = element_rect(size = 4),
    legend.key.height = unit(1.3, "cm"),
    legend.key.width = unit(1.3, "cm"))

它产生了这两个图:

CDF plot

PDF plot

从图片中可以看出,两个地块中的灰色区域没有相同的高度。是否有某种方法可以预定义绘图边距,这样如果绘图彼此相邻放置,则在报表中,它们的高度相同等。 先感谢您!!

1 个答案:

答案 0 :(得分:1)

这是一个简短的例子。我们创建了两个图,我在第二个图中为x轴标签添加了一条新线,以使绘图区域具有不同的高度:

library(ggplot2)
p1 <- ggplot(mtcars, aes(x = mpg)) +
  stat_ecdf()
p2 <- ggplot(mtcars, aes(x = mpg)) +
  stat_density() +
  labs(x = "mpg\n")

我们使用grid.arrange包中的gridExtra函数来查看这些图表是如何并排显示的:

gridExtra::grid.arrange(p1, p2, nrow = 1)

enter image description here

plot_grid包中的cowplot函数允许我们对齐轴:

cowplot::plot_grid(p1, p2, align = "h")

enter image description here