grid.arrange显示空图

时间:2019-04-20 16:16:27

标签: r ggplot2

我已经在R中使用ggplot2创建了一些图。现在,我想使用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,即空情节:

image

1 个答案:

答案 0 :(得分:1)

不知道为什么,但是它只有在我们将其分配回变量后才起作用。当我用简单的时候没用

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