在ggplot2中的Facet累积和

4

我希望能够安排几个ggplot2图表。 对于直方图,以下代码可以完美运行:

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

现在我需要累积直方图,我按照 这个方法 去做。 但是它给出了错误的总和:
qplot(Temp, data=df, geom="histogram",binwidth=1)+
geom_histogram(aes(y=cumsum(..count..)),binwidth=1)+
facet_grid(Modul ~ .)

这里输入图片描述

虽然我大致明白正在发生什么,但我不够专业,无法解决。有什么提示吗?

最好的祝福, Jochen

3个回答

5
这里可能存在一个顺序问题:在对内部生成的变量(这里使用stat“bin”引擎)应用函数之前,您无法进行分面。因此,正如其他答案中提到的那样,您需要在外部进行计算。
我建议:
  1. 使用geom_histogram获取统计内部引擎生成的数据
  2. 使用生成的数据,在ggplot2之外按组计算累积计数
  3. 绘制新数据的条形图

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

我更喜欢这个解决方案。它更快,直接解决了不整齐的右边缘问题。谢谢! - Jochen Döll

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

这将产生一个合理的图形,带有信息丰富但不整齐的右边缘。 每组累积直方图


1
最好事先转换数据,然后再绘制图表。由于“累积直方图”不是常见的图表类型,我认为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~.)

我希望这有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接