【问题标题】:Generating a stacked cumulative smooth frequency distribution plot生成堆叠累积平滑频率分布图
【发布时间】:2015-12-03 15:39:27
【问题描述】:

我的数据中记录了两种类型的出现: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曲线之间的区域为另一种颜色。

【问题讨论】:

    标签: r ggplot2 ecdf


    【解决方案1】:

    您可以在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()
    

    【讨论】:

    • 感谢 jeremycg。我收到了这个错误: 完成错误(df %&gt;% group_by(type, year) %&gt;% summarise(total = n()) %&gt;% mutate(total = cumsum(total)) %&gt;% ungroup, : 未使用的参数(填充 = 列表(总计 = 0))
    • 您可能有一个过时的tidyr 版本,仅在 v0.30 中添加了完整版本。尝试重新安装它。
    猜你喜欢
    • 1970-01-01
    • 2018-07-04
    • 1970-01-01
    • 2012-10-16
    • 1970-01-01
    • 1970-01-01
    • 2012-06-24
    • 2013-03-02
    • 1970-01-01
    相关资源
    最近更新 更多