如何在ggplot2中的直方图中叠加具有相应binwidth值的列的平均值

时间:2015-07-15 01:25:19

标签: r plot ggplot2 histogram

如何在以下直方图中插入“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”的平均值。 我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:2)

您需要建立与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")

enter image description here

可悲的是,它看起来很糟糕,因为尺度并不相似。