2015-10-15 135 views
1

平均假设我有一个数据帧,看起来像这样:ggplot:绘制在x轴上的垃圾箱和y轴

data <- data.frame(y = rnorm(10,0,1), x = runif(10,0,1)) 

我想要做的是削减x值成箱,如:

data$bins <- cut(data$x,breaks = 4) 

然后,我想的方式,x轴是仓(使用ggplot)的结果来绘制,并且y轴是数据$ y的数据点的平均值落入相应的垃圾箱。

预先感谢您

+0

我看到你的问题问切值,然后绘制平均值。使用象''tmp < - hist(data.x,breaks =“Sturges”)这样的'hist'函数中的标准算法来寻找箱子,然后使用类似'idxs = findInterval(data.x) ,tmp $ break)'。然后使用ggplot中的x坐标索引:'tmp $ mids [idxs]'和使用@christoph建议的解决方案的y平均值。 – Sid

回答

3

可以使用stat_summary()功能。

library(ggplot2) 
data <- data.frame(y = rnorm(10,0,1), x = runif(10,0,1)) 
data$bins <- cut(data$x,breaks = 4) 
# Points: 
ggplot(data, aes(x = bins, y = y)) + 
    stat_summary(fun.y = "mean", geom = "point") 

# Histogram bars: 
ggplot(data, aes(x = bins, y = y)) + 
    stat_summary(fun.y = "mean", geom = "histogram") 

这里是点的画面:

enter image description here

1

由于您的y值的平均值可以小于0,我推荐一个点图,而不是条形图。点代表手段。您可以使用qplot或常规ggplot函数。后者更具可定制性。在这个例子中,两者都产生相同的输出。

library(ggplot2) 

set.seed(7) 
data <- data.frame(y = rnorm(10,0,1), x = runif(10,0,1)) 
data$bins <- cut(data$x,breaks = 4, dig.lab = 2) 

qplot(bins, y, data = data, stat="summary", fun.y = "mean") 

ggplot(data, aes(x = factor(bins), y = y)) + 
    stat_summary(fun.y = mean, geom = "point") 

您还可以添加错误栏。在这种情况下,它们显示组平均值+/- 1.96倍的组标准偏差。组平均值和SD可以使用tapply获得。

m <- tapply(data$y, data$bins, mean) 
sd <- tapply(data$y, data$bins, sd) 
df <- data.frame(mean.y = m, sd = sd, bin = names(m)) 

ggplot(df, aes(x = bin, y = mean.y, 
       ymin = mean.y - 1.96*sd, 
       ymax = mean.y + 1.96*sd)) + 
    geom_errorbar() + geom_point(size = 3) 

enter image description here