我的数据中注册了两种类型的事件:type_a 和 type_b 及其发生年份。
这是生成数据示例的一种方法:
set.seed(1)
years <- 1991:2010
type_a_years <- 20
type_b_years <- 10
type_a <- round(runif(type_a_years, 0, 5))
type_b <- c(rep(0, type_a_years-type_b_years),round(runif(type_b_years, 5, 7)))
df <- data.frame(year = unlist(sapply(1:length(years), function(x) c(rep(years[x], type_a[x]),rep(years[x], type_b[x])))),
type = unlist(sapply(1:length(years), function(x) c(rep("type_a", type_a[x]),rep("type_b", type_b[x])))))
head(df)
year type
1 1991 type_a
2 1992 type_a
3 1992 type_a
4 1993 type_a
5 1993 type_a
6 1993 type_a
我想生成按年份堆叠在 type_a 事件之上的 type_b 事件的累积频率分布图,并且我希望分布显示为曲线而不是条形。
我猜这应该是一些操纵:
library(ggplot2)
ggplot(df, aes(year)) + stat_ecdf()
我将得到两条曲线并按类型堆叠,其中每种类型下方的区域将填充不同的颜色。也就是说,type_a 曲线和 x 轴之间的区域将采用一种颜色,而 type_b 曲线和 type_a 曲线之间的区域将采用另一种颜色。
最佳答案
您可以使用 dplyr
和 tidyr
中的一些聚合来完成此操作,然后使用 geom_area
。
library(tidyr)
library(dplyr)
df1 <- df %>% group_by(type, year) %>%
summarise(total = n()) %>%
mutate(total = cumsum(total)) %>%
ungroup %>%
complete(type, year, fill = list(total = 0))
现在绘制:
library(ggplot2)
ggplot(df1, aes(x = year, y = total, fill = type)) + geom_area()
关于r - 生成堆积累积平滑频率分布图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34070062/