简体   繁体   English

区域 plot 使用 R tidyverse、ggplot、geom_area

[英]Area plot using R tidyverse, ggplot, geom_area

I am using the follow code to generate an area plot using tidyverse , ggplot function and geom_area .我正在使用以下代码使用tidyverseggplot function 和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")

This works, but there are two open triangles at the bottom, which I would like to have filled with green and blue, respectively.这可行,但底部有两个开放的三角形,我想分别用绿色和蓝色填充。 I thought I could solve this by changing the code like this:我想我可以通过改变这样的代码来解决这个问题:

 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")

But now the plotting does not work at all anymore.但是现在绘图根本不起作用了。 This post did not help me. 这篇文章对我没有帮助。 Could anybody help, please?请问有人可以帮忙吗?

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")

ggplot2 带孔的面积图

If the ramp-up for the first group is a problem, then we can take it out simply:如果第一组的加速有问题,那么我们可以简单地解决它:

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")

第一组没有斜坡的相同情节

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM