I'm looking for an easier way to draw the cumulative distribution line in ggplot.
I have some data whose histogram I can immediately display with
qplot (mydata, binwidth=1);
I found a way to do it at http://www.r-tutor.com/elementary-statistics/quantitative-data/cumulative-frequency-graph but it involves several steps and when exploring data it's time consuming.
Is there a way to do it in a more straightforward way in ggplot, similar to how trend lines and confidence intervals can be added by specifying options?
В 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()
Edit Я только что понял, что вам нужна кумулятивная частота. Вы можете получить ее, умножив значение 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))