how can insert mean value of "ele" in following histogram.
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 here trying insert mean of "ele" belongs each binwidth , not "ele" points. how can achieve that?
you need establish grouping of ele corresponds the bins created geom_histogram. outside of ggplot call using method of aggregating data. here example using dplyr means of histogram groups. may want @ stat_summary option.
library(ggplot2) p1 <- ggplot(dfsample, aes(value)) + geom_histogram(binwidth=0.01, fill="aquamarine4", colour="black") ## 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 define grouping 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 means points p1 + geom_point(data=dat, aes(group, y), color="red") 
sadly, looks terrible because scales aren't similar.
Comments
Post a Comment