更简单的方法来绘制ggplot中的累积频率分布?

时间:2010-08-23 00:08:25

标签: r ggplot2

我正在寻找一种更简单的方法来在ggplot中绘制累积分布线。

我有一些数据,其直方图我可以立即显示

qplot (mydata, binwidth=1);

我在http://www.r-tutor.com/elementary-statistics/quantitative-data/cumulative-frequency-graph找到了一种方法,但它涉及几个步骤,在探索数据时耗费时间。

有没有办法在ggplot中以更直接的方式进行,类似于如何通过指定选项添加趋势线和置信区间?

3 个答案:

答案 0 :(得分:55)

新版本的ggplot2(0.9.2.1)有一个内置的stat_ecdf()功能,可以让你很容易地绘制累积分布。

qplot(rnorm(1000), stat = "ecdf", geom = "step")

或者

df <- data.frame(x = c(rnorm(100, 0, 3), rnorm(100, 0, 10)),
             g = gl(2, 100))
ggplot(df, aes(x, colour = g)) + stat_ecdf()

ggplot2文档中的代码示例。

答案 1 :(得分:24)

R中有一个内置的ecdf()函数,可以让事情变得更容易。以下是一些示例代码,使用plyr

library(plyr)
data(iris)

## Ecdf over all species
iris.all <- summarize(iris, Sepal.Length = unique(Sepal.Length), 
                            ecdf = ecdf(Sepal.Length)(unique(Sepal.Length)))

ggplot(iris.all, aes(Sepal.Length, ecdf)) + geom_step()

#Ecdf within species
iris.species <- ddply(iris, .(Species), summarize,
                            Sepal.Length = unique(Sepal.Length),
                            ecdf = ecdf(Sepal.Length)(unique(Sepal.Length)))

ggplot(iris.species, aes(Sepal.Length, ecdf, color = Species)) + geom_step()

编辑我刚才意识到你想要累积频率。您可以通过将ecdf值乘以观察总数来得到它:

iris.all <- summarize(iris, Sepal.Length = unique(Sepal.Length), 
                            ecdf = ecdf(Sepal.Length)(unique(Sepal.Length)) * length(Sepal.Length))

iris.species <- ddply(iris, .(Species), summarize,
                            Sepal.Length = unique(Sepal.Length),
                            ecdf = ecdf(Sepal.Length)(unique(Sepal.Length))*length(Sepal.Length))

答案 2 :(得分:21)

更容易:

qplot(unique(mydata), ecdf(mydata)(unique(mydata))*length(mydata), geom='step')
相关问题