首页 > 解决方案 > grid.arrange 显示空图

问题描述

我已经使用ggplot2R 创建了一些图。现在,我想使用 合并两个图grid.arrange,但是在使用此函数后,我只得到空图。

我也试过cowplot图书馆,但我遇到了同样的问题。

## Pipe age distribution in the initial pipe network conditions
pipe_age_0 = 2019 + net.ini$time.construction
pipe_age = 2019 - pipe_age_0

p6 <- ggplot(net.ini, aes(x = pipe_age))
p6 + geom_histogram(binwidth = 1,
                    col="black",
                    size=0.1,
                    fill = "lightgrey") +
     scale_x_continuous(breaks = seq(from = 0, to = 140, by = 10)) +
     labs(y="Count", x="Age [Years]") +
     theme_bw(base_size = 12, base_family = "")

## Density stacked with histogram count
p7 <- ggplot(net.ini, aes(x = pipe_age))
p7 + geom_histogram(aes(y = ..density..),
                    binwidth = 1,
                    col="black",
                    size=0.1,
                    fill = "lightgrey") +
  geom_density(alpha = 0.1, fill="#FF6666") +
  scale_x_continuous(breaks = seq(from = 0, to = 140, by = 10)) +
  labs(y="Density", x="Age [Years]") +
  theme_bw(base_size = 12, base_family = "")

grid.arrange(p6, p7)

我希望有两张图一个在另一个之上,或者一个在另一个旁边使用grid.arrange. 但是由于某种原因,我不断得到空的情节。这是图 p6 和 p7 的样子,第三个带有grid.arrange,空图:

图片

标签: rggplot2

解决方案


不知道为什么,但它只有在我们将它分配回变量后才能工作。当我使用简单时没有工作

p <- ggplot(df)
p + geom_col(aes(x,y))

所以尝试这样的事情:

p7 <- ggplot(net.ini, aes(x = pipe_age))
p7 <- p7 + geom_histogram(aes(y = ..density..),
                    binwidth = 1,
                    col="black",
                    size=0.1,
                    fill = "lightgrey") +
  geom_density(alpha = 0.1, fill="#FF6666") +
  scale_x_continuous(breaks = seq(from = 0, to = 140, by = 10)) +
  labs(y="Density", x="Age [Years]") +
  theme_bw(base_size = 12, base_family = "")

适用于两者cowplotgrid.arrange


推荐阅读