在ggplot2中的Facet累积总和

时间:2014-09-30 08:49:05

标签: r

我想安排好几个ggplot2-plot。 它对于直方图非常适用,使用以下代码:

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

enter image description here

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

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

enter image description here

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

祝你好运, 约亨

3 个答案:

答案 0 :(得分:3)

这可能是一个有序的问题:我认为在将函数应用于内部生成的变量(这里是stat“bin”引擎)之前,你不能进行分面。因此,正如其他人的回答所提到的,你需要在外面进行计算。

我会:

  1. 使用geom_histogram通过统计内部引擎
  2. 创建数据
  3. 使用生成的数据计算ggplot2之外的组的累计计数。
  4. 绘制新数据的条形图
  5. enter image description here

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

答案 1 :(得分: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~.)

给出了一个合理的图形,其中包含了信息丰富但边缘粗糙的图形。 cumulative histogram by group

答案 2 :(得分:1)

最好的方法是事先转换数据然后绘制它。由于&#34;累积直方图&#34;不是一个常见的图表类型,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~.)

我希望有所帮助。

相关问题