我正在使用以下代码使用tidyverse
,ggplot
函数和生成面积图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")
如果第一个小组的晋升有问题,那么我们可以简单地将其删除:
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")
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句