【问题标题】:ggplot: Plotting the bins on x-axis and the average on y-axisggplot:在 x 轴上绘制 bin,在 y 轴上绘制平均值
【发布时间】:2015-10-15 14:16:40
【问题描述】:

假设我有一个如下所示的数据框:

data <- data.frame(y = rnorm(10,0,1), x = runif(10,0,1))

我想做的是将x值切割成bin,例如:

data$bins <- cut(data$x,breaks = 4)

然后,我想绘制(使用 ggplot)结果,其中 x 轴是 bin,y 轴是落入相应 bin 的 data$y 数据点的平均值。

提前谢谢你

【问题讨论】:

  • 我看到你的问题要求削减价值,然后绘制平均值。使用hist 函数(如&gt; tmp &lt;- hist(data.x, breaks="Sturges") )中的标准算法,然后使用idxs = findInterval(data.x, tmp$breaks) 之类的算法,在统计上更合理的方法。然后使用 ggplot 中 x 坐标的索引:tmp$mids[idxs] 和 y 的平均值,使用@christoph 建议的解决方案。

标签: r ggplot2 binning


【解决方案1】:

您可以使用stat_summary() 函数。

library(ggplot2)
data <- data.frame(y = rnorm(10,0,1), x = runif(10,0,1))
data$bins <- cut(data$x,breaks = 4)
# Points:
ggplot(data, aes(x = bins, y = y)) +
  stat_summary(fun.y = "mean", geom = "point")

# Histogram bars:
ggplot(data, aes(x = bins, y = y)) +
  stat_summary(fun.y = "mean", geom = "histogram")

这是点的图片:

【讨论】:

    【解决方案2】:

    这个帖子有点老了,但是你去吧,使用 stat_summary_bin(它可能在较新的版本中)。

    ggplot(data, mapping=aes(x, y)) +
    stat_summary_bin(fun.y = "mean", geom="bar", bins=4 - 1) +
    ylab("mean")
    

    【讨论】:

      【解决方案3】:

      由于 y 值的平均值可能小于 0,因此我建议使用点图而不是条形图。点代表手段。您可以使用 qplot 或常规 ggplot 函数。后者更可定制。在此示例中,两者都产生相同的输出。

      library(ggplot2)
      
      set.seed(7)
      data <- data.frame(y = rnorm(10,0,1), x = runif(10,0,1))
      data$bins <- cut(data$x,breaks = 4, dig.lab = 2)
      
      qplot(bins, y, data = data, stat="summary", fun.y = "mean")
      
      ggplot(data, aes(x = factor(bins), y = y)) + 
        stat_summary(fun.y = mean, geom = "point")
      

      您还可以添加误差线。在这种情况下,它们显示平均值 +/- 1.96 倍的组标准差。使用tapply可以获得组均值和SD。

      m <- tapply(data$y, data$bins, mean)
      sd <- tapply(data$y, data$bins, sd)
      df <- data.frame(mean.y = m, sd = sd, bin = names(m))
      
      ggplot(df, aes(x = bin, y = mean.y, 
                     ymin = mean.y - 1.96*sd, 
                     ymax = mean.y + 1.96*sd)) + 
        geom_errorbar() + geom_point(size = 3)
      

      【讨论】: