【问题标题】:Easier way to plot the cumulative frequency distribution in ggplot?在ggplot中绘制累积频率分布的更简单方法?
【发布时间】:2011-04-02 10:06:58
【问题描述】:

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

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

qplot (mydata, binwidth=1);

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

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

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    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))
    

    【讨论】:

    • 这是一个很好的答案,但有一件事我不太明白。在ecdf(Sepal.Length)(unique(Sepal.Length)) 位中,发生了什么?我知道它正在从 ecdf 对象中提取具体值,但我不记得以前见过 (x)(y) 符号……你能帮我理解吗?谢谢!
    • @MattParker ecdf() 返回一个函数,以便符号以 Sepal.Length 的唯一值评估返回的函数。
    【解决方案2】:

    更简单:

    qplot(unique(mydata), ecdf(mydata)(unique(mydata))*length(mydata), geom='step')
    

    【讨论】:

    • 酷,但如此简洁,我很难翻译成可以用来设置标题和轴标签的 ggplot 命令。
    • 我想我可以使用 main、xlab、ylab。
    • 它如何与构面交互?
    【解决方案3】:

    新版本的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 文档中的代码示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-02
      • 1970-01-01
      • 1970-01-01
      • 2014-11-20
      • 1970-01-01
      • 1970-01-01
      • 2017-12-23
      • 1970-01-01
      相关资源
      最近更新 更多