R ggplot2中的分面累积和

R ggplot2中的分面累积和,r,R,我想安排几个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 ~ .) 虽然我大致了解正在发生的事情,但我还没有足够

我想安排几个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 ~ .)

虽然我大致了解正在发生的事情,但我还没有足够的专家来解决这个问题。 有什么提示吗

致以最良好的祝愿,
Jochen

我的理解是,在绘制统计数据和计算统计数据之间存在一种有意的分离。因此,虽然ggplot通常可以调用简单的统计计算,但这是一个不那么容易的例子。 从这个角度来看,预先计算感兴趣的统计数据是有意义的

以下是使用ddply预先计算累积直方图的示例:

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

df最好是事先转换数据,然后绘制它。由于“累积直方图”不是一种常见的图表类型,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~.)
库(ggplot2)
图书馆(dplyr)
#按binned Temp和Modul生成计数,并将其另存为新data.frame
#trunc()是一个快速修复程序,您可以使用任何聚合/组合函数

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

我想:

  • 使用
    geom_直方图
    获取通过统计内部引擎创建数据的方法
  • 使用生成的数据计算ggplot2之外的分组累计计数
  • 绘制新数据的条形图

  • p我更喜欢这个解决方案。它更快,直接解决了不规则的右边缘问题。非常感谢。
    
    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~.)
    
    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")