【问题标题】:How to overlay mean of a column with corresponding binwidth values in histogram in ggplot2如何在ggplot2的直方图中覆盖具有相应binwidth值的列的平均值
【发布时间】:2015-07-15 01:25:18
【问题描述】:

如何在下面的直方图中插入“ele”的平均值。

dput(dfsample)
structure(list(value = c(0.0335026912575717, 0.0345000229569703, 
 0.0354186209415201, 0.038902323373206, 0.0426493324589743, 0.0321982282442823, 
0.033229179855505, 0.0349933075439487, 0.036071015613386, 0.036286798879435
), ele = c(721L, 749L, 700L, 665L, 674L, 677L, 747L, 900L, 869L, 
774L)), .Names = c("value", "ele"), row.names = c(840L, 841L, 
842L, 843L, 844L, 833L, 834L, 835L, 836L, 837L), class = "data.frame")

p1<-ggplot(dfsample, aes(value)) +
  geom_histogram(binwidth=0.01,fill="aquamarine4", colour="black")+
  geom_point(aes(y=ele))
p1

这里我要做的是插入属于每个 binwidth 而不是所有“ele”点的“ele”的平均值。 我怎样才能做到这一点?

【问题讨论】:

  • 这将如何工作?请注意,直方图绘制计数(您的示例上升到 8-ish)但 ele 在 600 或 700 内,因此即使您为直方图上的每个 bin 绘制平均值 ele,y 轴也是不同的, ele 的平均值会很高(600-700ish),以至于直方图看起来像一条平线。

标签: r plot ggplot2 histogram


【解决方案1】:

您需要建立ele 的分组,该分组对应于使用geom_histogram 创建的垃圾箱。您可以使用某种聚合数据的方法在 ggplot 调用之外执行此操作。这是一个使用dplyr 获取直方图组均值的示例。您可能希望将stat_summary 作为另一种选择。

library(ggplot2)
p1 <- ggplot(dfsample, aes(value)) +
  geom_histogram(binwidth=0.01, fill="aquamarine4", colour="black")

## Get the histogram breaks
stuff <- ggplot_build(p1)
breaks <- with(stuff[[1]][[1]], c(xmin, xmax[length(xmax)]))
mids <- stuff[[1]][[1]]$x  # midpoints of bins

## use those to define the grouping to get means
dfsample$group <- cut(dfsample$value, breaks=breaks)
library(dplyr)
dfsample %>% group_by(group) %>%
  summarise(y=mean(ele)) %>%
  mutate(group = mids[as.integer(group)]) -> dat

## add the means as points
p1 + geom_point(data=dat, aes(group, y), color="red")

遗憾的是,它看起来很糟糕,因为尺度不相似。

【讨论】:

  • @nongkorng 谢谢。现在将尝试在右 y 轴上绘制 ele。虽然在 ggplot2 中似乎很复杂。
猜你喜欢
  • 1970-01-01
  • 2012-10-09
  • 1970-01-01
  • 2018-08-02
  • 2021-12-16
  • 1970-01-01
  • 2011-10-20
  • 2017-04-25
  • 1970-01-01
相关资源
最近更新 更多