[英]How can I plot a cumulative distribution function (CDF) for binned data?
我有离散数据,例如在范围内呈现
Marks Freq cumFreq
1 (37.9,43.1] 4 4
2 (43.1,48.2] 16 20
3 (48.2,53.3] 76 96
我需要为这些数据绘制 cmf,我知道有
plot(ecdf(x))
但我不知道要添加什么才能拥有我需要的东西。
这里有几个选项:
library(ggplot2)
library(scales)
library(dplyr)
## Fake data
set.seed(2)
dat = data.frame(score=c(rnorm(130,40,10), rnorm(130,80,5)))
如果您有原始数据,以下是绘制 ECDF 的方法:
# Base graphics
plot(ecdf(dat$score))
# ggplot2
ggplot(dat, aes(score)) +
stat_ecdf(aes(group=1), geom="step")
如果您只有汇总数据,这是绘制 ECDF 的一种方法:
首先,让我们将数据分组到 bin 中,类似于您在问题中的情况。 我们使用cut
函数创建 bin,然后创建一个新的pct
列来计算每个 bin 占分数总数的分数。 我们使用dplyr
链接运算符 ( %>%
) 在一个“函数链”中完成所有操作。
dat.binned = dat %>% count(Marks=cut(score,seq(0,100,5))) %>%
mutate(pct = n/sum(n))
现在我们可以绘制它。 cumsum(pct)
计算累积百分比(如您问题中的cumFreq
)。 geom_step
使用这些累积百分比创建阶梯图。
ggplot(dat.binned, aes(Marks, cumsum(pct))) +
geom_step(aes(group=1)) +
scale_y_continuous(labels=percent_format())
以下是情节的样子:
这个怎么样:
library(ggplot2)
library(scales)
library(dplyr)
set.seed(2)
dat = data.frame(score = c(rnorm(130,40,10), rnorm(130,80,5)))
dat.binned = dat %>% count(Marks = cut(score,seq(0,100,5))) %>%
mutate(pct = n/sum(n))
ggplot(data = dat.binned, mapping = aes(Marks, cumsum(pct))) +
geom_line(aes(group = 1)) +
geom_point(data = dat.binned, size = 0.1, color = "blue") +
labs(x = "Frequency(Hz)", y = "Axis") +
scale_y_continuous(labels = percent_format())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.