1
使用mtcars数据集(GGPLOT2)平均y值我做计算在Windows
library(ggplot2)
plot(mtcars$mpg, mtcars$qsec)
现在我想在不同的点,但使用Windows来计算SD。因此,要在10至15,15至20,20至25等的区间内获得sd估计值。战后,我想在每个窗口中显示差异作为错误栏。
使用mtcars数据集(GGPLOT2)平均y值我做计算在Windows
library(ggplot2)
plot(mtcars$mpg, mtcars$qsec)
现在我想在不同的点,但使用Windows来计算SD。因此,要在10至15,15至20,20至25等的区间内获得sd估计值。战后,我想在每个窗口中显示差异作为错误栏。
下面介绍一种方法。您可以计算您希望作为数据框中新列的值。然后计算平均值和标准差。每个组的错误,然后绘制方法并将错误条叠加在上面。
buckets <- c(10,15,20,25,30,35)
mtcars$mpg_bucket <- cut(mtcars$mpg, buckets) #create a new column
#group by bucket and calculate mean qsec
mean_qsec <- tapply(mtcars$qsec, mtcars$mpg_bucket, mean)
#se for bucket = sd/ sqrt(count)
stderr <- tapply(mtcars$qsec, mtcars$mpg_bucket, function(x){sd(x)/sqrt(length(x))})
# Define the top and bottom of the errorbars
limits <- aes(ymax = mean_qsec + stderr, ymin= mean_qsec - stderr)
df <- data.frame(mean_qsec, stderr)
df$buckets <- row.names(df)
ggplot(df, aes(x=buckets, y=mean_qsec)) + geom_bar(stat="identity", fill="gray70") +
geom_errorbar(limits,width=0.25)
这产生: