【问题标题】:Facet Cumulative sums in ggplot2ggplot2中的方面累积和
【发布时间】:2014-09-30 08:49:04
【问题描述】:

我想安排几个 ggplot2-plots。 它适用于直方图,使用以下代码:

df<-NULL
df$Temp<-rnorm(mean=20,sd=3,n=100) 
df$Modul<-rep(seq(1,4,1),25)
df<-as.data.frame(df)   

qplot(Temp, data=df, geom="histogram",binwidth=1)+
    facet_grid(Modul ~ .)

现在我想要累积直方图,我关注了this recipy。 但它给了我错误的总和:

qplot(Temp, data=df, geom="histogram",binwidth=1)+
geom_histogram(aes(y=cumsum(..count..)),binwidth=1)+
facet_grid(Modul ~ .)

虽然我大致了解发生了什么,但我不够专业,无法解决这个问题。 有什么提示吗?

最好的问候, 乔辰

【问题讨论】:

    标签: r


    【解决方案1】:

    这可能是一个顺序问题:我认为在将函数应用于内部生成的变量(这里是 stat "bin" 引擎)之前,你不能做 faceting。因此,正如其他答案中提到的,您需要在外部进行计算。

    我愿意:

    1. 使用geom_histogram获取内部统计引擎创建的数据
    2. 使用生成的数据按 ggplot2 之外的组计算累积计数。
    3. 绘制新数据的条形图

    p <- ggplot(df,aes(x=Temp))+
      geom_histogram(binwidth=1)+facet_grid(Modul~.)
    
    dat <-  ggplot_build(p)$data[[1]]
    library(data.table)
    ggplot(setDT(dat)[,y:=cumsum(y),"PANEL"],aes(x=x)) +
      geom_bar(aes(y=y,fill=PANEL),stat="identity")+facet_grid(PANEL~.) +
      guides(title="Modul")
    

    【讨论】:

    • 我更喜欢这个解决方案。它更快,直接解决了参差不齐的右边缘问题。谢谢!
    【解决方案2】:

    我的理解是,绘图和计算统计数据之间存在预期的分离。因此,虽然 ggplot 通常可以调用简单的统计计算,但这是一个不太容易的示例。 使用这种视图,预先计算感兴趣的统计数据是有意义的。

    这是一个使用 ddply 预先计算累积直方图的示例:

    df <- ddply(df,.(Modul),mutate,count=rank(Temp))
    ggplot(df)+geom_ribbon(aes(x=Temp,ymax=count),ymin=0)+facet_grid(Modul~.)
    

    它给出了一个合理的图形,其信息丰富但右边缘参差不齐。

    【讨论】:

      【解决方案3】:

      最好的办法是事先转换数据,然后绘制它。由于“累积直方图”不是一种常见的图表类型,因此 ggplot(据我所知)没有内置的方法来处理它。

      这就是我的做法:

      library(ggplot2)
      library(dplyr)
      
      # generate counts by binned Temp and Modul, save it as a new data.frame
      # trunc() is a quick fix, you can use any aggregating/binning function
      df.counts <- as.data.frame(table(trunc(df$Temp), df$Modul))
      names(df.counts) <- c("Temp", "Modul", "count")  ## fix names
      
      # generate grouped cumsum using dplyr, you can also use data.table for this
      df.counts <- df.counts %>% group_by(Modul) %>% mutate(cumulative = cumsum(count))
      
      # use a barplot to get what you want (geom_histogram is essentially the same)
      ggplot(df.counts) + 
        geom_bar(aes(x=Temp, y=cumulative), stat="identity", width=1) + 
        facet_grid(Modul~.)
      

      希望对你有帮助。

      【讨论】:

        猜你喜欢
        • 2013-08-23
        • 1970-01-01
        • 1970-01-01
        • 2013-03-28
        • 1970-01-01
        • 2021-05-10
        • 1970-01-01
        • 1970-01-01
        • 2016-03-18
        相关资源
        最近更新 更多