2016-11-30 69 views
0

我试图使用gridExtra软件包将三个图彼此堆叠在一起。我已经尝试了使用heregrid.arrange的第一个示例,该示例非常好。使用gridExtra(ggplot)的好奇行为

但是,当我尝试使用自己的情节时,我得到了每个情节的轴但没有数据,所有格式都被消除了。最低工作例如:

library(ggplot2) 
library(gridExtra)  

popu_H0 <- seq(10, 30, length=100) 
popu_H0_norm <- dnorm(popu_H0, mean = 20, sd = 4) 

popu_H0_df <- as.data.frame(cbind(popu_H0, popu_H0_norm)) 
plot_H0 <- ggplot(popu_H0_df, aes(x=popu_H0, y=popu_H0_norm)) 
plot_H0 + 
    geom_line() + 
    theme(
    text = element_text(size=20), 
    axis.title.x = element_text(vjust=0.1), 
    axis.text.x = element_text(size = rel(1.8)), 
    legend.position = "none", 
    axis.title.y = element_blank(), 
    axis.text.y = element_blank(), 
    axis.ticks.y = element_blank(), 
    axis.line.y = element_blank() 
) + 
    xlab("New label") + 
    annotate("text", x = 20, y = 0.05, label = "Some annotation", size = 10) 

grid.arrange(plot_H0, plot_H0, plot_H0, ncol = 1, nrow = 3) 

ggplot产生预期的输出,但grid.arrange产生this

回答

1

您忘记更换绘图对象。

library(ggplot2) 
library(gridExtra) 
popu_H0 <- seq(10, 30, length=100) 
popu_H0_norm <- dnorm(popu_H0, mean = 20, sd = 4) 

popu_H0_df <- as.data.frame(cbind(popu_H0, popu_H0_norm)) 
plot_H0 <- ggplot(popu_H0_df, aes(x=popu_H0, y=popu_H0_norm)) 
plot_H0 <- plot_H0 + # Here you need `<-` to update the plot 
    geom_line() + 
    theme(
    text = element_text(size=20), 
    axis.title.x = element_text(vjust=0.1), 
    axis.text.x = element_text(size = rel(1.8)), 
    legend.position = "none", 
    axis.title.y = element_blank(), 
    axis.text.y = element_blank(), 
    axis.ticks.y = element_blank(), 
    axis.line.y = element_blank() 
) + 
    xlab("New label") + 
    annotate("text", x = 20, y = 0.05, label = "Some annotation", size = 10) 

grid.arrange(plot_H0, plot_H0, plot_H0, ncol = 1, nrow = 3) 
+0

感谢您的回复。但是,我错过了什么?您发布的代码看起来与我的代码完全相同,除非(正确)在顶部添加了库调用。也许线索是在“你忘了更换剧情对象”,但我不知道这意味着什么!如果你指的是我已经使用了同样的情节3次,我可以确认这种行为与三个不同的情节对象完全相同。我只是以这种方式发布它,以使这个例子简单和可重复。 – suknat

+0

我在第七行有'plot_H0 < - '。我在那里添加评论。 –

+0

辉煌和感谢!对不起,我没有发现! – suknat