4

我正在尝试创建一个直方图,其中 bin 高度是落入每个 bin 的值的平均值。下面 p2 的代码是我认为可行的。

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

抱歉,如果我在这里遗漏了一些明显的东西,但我感谢您的帮助。

4

2 回答 2

4

您现在可以使用stat_summary_bin它。

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

在此处输入图像描述

于 2020-07-07T05:14:37.680 回答
2

您可以使用以下方法计算均值:

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();

在此处输入图像描述

于 2012-11-16T01:46:17.477 回答