Doug Mitarotonda
Doug Mitarotonda

Reputation: 107

Histogram of mean per bin

I am trying to create a histogram where the bin heights are the mean of the values that fall into each bin. The code for p2 below is what I thought would work.

library(ggplot2)
m <- mtcars[1:20, ];
p <- ggplot(m, aes(x = mpg)) + geom_histogram(binwidth = 5);
p <- p + aes(weight = wt); # works, but is the sum of the wt
p2 <- p + aes(weight = wt / ..count..); # does not work, but the idea I am going for

Sorry if I am missing something obvious here, but I appreciate the help.

Upvotes: 5

Views: 3766

Answers (2)

Harry M
Harry M

Reputation: 2088

You can now use stat_summary_bin for this.

ggplot(mtcars, aes(x=mpg, y=wt)) +
  stat_summary_bin(fun.y = "mean",
                   geom="bar",
                   binwidth=5
                   )

enter image description here

Upvotes: 5

JRideout
JRideout

Reputation: 1635

You could just calculate the means with something like this:

m <- mtcars[1:20, ];
m$br <- cut(m$mpg,hist(m$mpg,5,plot=F)$breaks);
mean.wt <- tapply(m$wt,m$br,mean);
m2 <- data.frame(mpg.bin=names(mean.wt),mean.wt);
ggplot(m2,aes(x=mpg.bin,y=mean.wt)) + geom_bar();

enter image description here

Upvotes: 2

Related Questions