首页 文章

在R图中绘制平均值

提问于
浏览
-2

我想在我的散点图中为窗口添加一个值的平均值 . 我用ggplot2创建了散点图

p <- ggplot(mtcars, aes(wt, mpg)) 
p + geom_point()

这将给出散点图,但我想添加一个窗口的平均值(比如大小等于1)并将这个均值点绘制成一条线 . 另外,我想在每个点都有竖条来表示方差 .

Mtcars是ggplot 2中提供的数据集标准

3 回答

  • 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))
    

    enter image description here

  • 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")
    

    enter image description here

  • 0

    这是你想要的吗?

    p <- ggplot(mtcars, aes(wt, mpg)) 
    p + geom_point() + geom_smooth(aes(wt, mpg, group=1), method = "lm")
    

    enter image description here

相关问题