使用 R tidyverse、ggplot、geom_area 的面积图

Area plot using R tidyverse, ggplot, geom_area

我正在使用以下代码使用 tidyverseggplot 函数和 geom_area.

生成面积图
 library(tidyverse)
 set.seed(12345)
 df1 <- data.frame(a = c(2000:2020), b = rnorm(21,25,4), c = rep("x", 21))
 df2 <- data.frame(a = c(2006:2020), b = rnorm(15,40,7), c = rep("y", 15))
 df3 <- data.frame(a = c(2017:2020), b = rnorm(4,20,3), c = rep("z", 4))
 df <- rbind(df1, df2, df3)
 ggplot(df, aes(x=a, y=b, fill=c)) + geom_area() + theme(legend.position = "none")

这可行,但底部有两个空心三角形,我想分别用绿色和蓝色填充。我想我可以通过像这样更改代码来解决这个问题:

 df1 <- data.frame(a = c(2000:2020), b = rnorm(21,25,4), c = rep("x", 21))
 df1 <- rbind(c("1999", "0","x"), df1)
 df2 <- data.frame(a = c(2006:2020), b = rnorm(15,40,7), c = rep("y", 15))
 df2 <- rbind(c("2005", "0","y"), df2)
 df3 <- data.frame(a = c(2017:2020), b = rnorm(4,20,3), c = rep("z", 4))
 df3 <- rbind(c("2016", "0","z"), df3)
 df <- rbind(df1, df2, df3)
 ggplot(df, aes(x=a, y=b, fill=c)) + geom_area(position=stack) + theme(legend.position = "none")

但是现在绘图完全不起作用了。 没有帮助我。有人可以帮忙吗?

library(dplyr)
df2 <- group_by(df, c) %>%
  summarize(a = min(a) - 1) %>%
  mutate(b = 0) %>%
  bind_rows(df) %>%
  arrange(a,c)
ggplot(df2, aes(x=a, y=b, fill=c)) +
  geom_area() +
  theme(legend.position = "none")

如果第一组的ramp-up有问题,那么我们可以简单的去掉:

df2 <- group_by(df, c) %>%
  summarize(a = min(a) - 1) %>%
  mutate(b = 0) %>%
  bind_rows(df) %>%
  arrange(a,c) %>%
  slice(-1)
ggplot(df2, aes(x=a, y=b, fill=c)) +
  geom_area() +
  theme(legend.position = "none")