r - 生成堆积累积平滑频率分布图

标签 r ggplot2 ecdf

我的数据中注册了两种类型的事件: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 曲线之间的区域将采用另一种颜色。

最佳答案

您可以使用 dplyrtidyr 中的一些聚合来完成此操作,然后使用 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()

enter image description here

关于r - 生成堆积累积平滑频率分布图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34070062/

相关文章:

r - 如何平滑 r 中的 ecdf 图

r - gt表中多列的条件格式

r - 用R中的值通过for循环填充3D矩阵

R ecdf 折线图上的高亮点

r - 在同一图中绘制 ecdf 和密度并放大到特定部分

r - ggplot2 -- 自动放大 geom_smooth(使用 coord_cartesian)

r - 使用 R 重命名文件

r - 子集和 ggplot2

r - 使用 R 数学符号时,ggplot geom_text 会弄乱文本顺序

r - 将计数标签添加到ggplot中比例数据的条形图中