我正在寻找一种更简单的方法来绘制ggplot中的累积分布线.
我有一些数据,我可以立即显示直方图
qplot (mydata, binwidth=1);
Run Code Online (Sandbox Code Playgroud)
我在http://www.r-tutor.com/elementary-statistics/quantitative-data/cumulative-frequency-graph找到了一种方法,但它涉及几个步骤,在探索数据时耗时.
有没有办法在ggplot中以更直接的方式执行此操作,类似于如何通过指定选项添加趋势线和置信区间?
Chr*_*ris 57
新版本的ggplot2(0.9.2.1)有一个内置的stat_ecdf()函数,可以让你很容易地绘制累积分布.
qplot(rnorm(1000), stat = "ecdf", geom = "step")
Run Code Online (Sandbox Code Playgroud)
要么
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()
Run Code Online (Sandbox Code Playgroud)
来自ggplot2文档的代码示例.
JoF*_*wld 26
ecdf()R中有一个内置函数,可以使事情变得更容易.这是一些示例代码,利用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()
Run Code Online (Sandbox Code Playgroud)
编辑我刚刚意识到你想要累积频率.你可以通过将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))
Run Code Online (Sandbox Code Playgroud)
Yan*_*ang 21
更简单:
qplot(unique(mydata), ecdf(mydata)(unique(mydata))*length(mydata), geom='step')
Run Code Online (Sandbox Code Playgroud)