代码之家  ›  专栏  ›  技术社区  ›  wishihadabettername

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

  •  28
  • wishihadabettername  · 技术社区  · 15 年前

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

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

    qplot (mydata, binwidth=1);
    

    http://www.r-tutor.com/elementary-statistics/quantitative-data/cumulative-frequency-graph 但它涉及到几个步骤,而且在探索数据时非常耗时。

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

    3 回复  |  直到 10 年前
        1
  •  27
  •   JoFrhwld    15 年前

    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
  •  61
  •   Chris    13 年前

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

        3
  •  21
  •   xyzzyrz    15 年前

    更简单:

    qplot(unique(mydata), ecdf(mydata)(unique(mydata))*length(mydata), geom='step')
    
    推荐文章