我想在我的散点图中为窗口添加一个值的平均值。我用ggplot2
创建了散点图 p <- ggplot(mtcars, aes(wt, mpg))
p + geom_point()
这将给出散点图,但我想添加一个窗口的平均值(比如大小等于1)并将这个均值点绘制成一条线。另外,我想在每个点都有竖条来表示方差。
Mtcars是ggplot 2中提供的数据集标准
答案 0 :(得分:2)
这使用新的dplyr库。
library(dplyr)
forLines <- mtcars %.%
group_by(cut(wt, breaks = 6)) %.%
summarise(mean_mpg = mean(mpg), mean_wt = mean(wt))
p +
geom_point(size=5) +
geom_boxplot(aes(group = cut(wt, breaks = 6))) +
geom_line(data=forLines,aes(x=mean_wt,y=mean_mpg))
答案 1 :(得分:1)
也许这就是你要找的东西:
library(ggplot2)
s <- seq(0, ceiling(max(mtcars$wt)), 1)
ind <- as.integer(cut(mtcars$wt, s))
myfun <- function(i)
c(y = mean(i), ymin = mean(i) - var(i), ymax = mean(i) + var(i))
ggplot(mtcars, aes(wt, mpg)) +
geom_point() +
stat_summary(fun.data = myfun, aes(group = ind, x = ind - .5),
colour = "red") +
stat_summary(fun.y = mean, aes(x = ind - .5), geom = "line",
colour = "red")
答案 2 :(得分:0)
这是你想要的吗?
p <- ggplot(mtcars, aes(wt, mpg))
p + geom_point() + geom_smooth(aes(wt, mpg, group=1), method = "lm")