【问题标题】:ggplot2 adding standard deviation of rolling mean to scatter graphggplot2将滚动平均值的标准差添加到散点图
【发布时间】:2021-06-04 20:46:01
【问题描述】:

我正在努力将滚动平均值的标准差映射到散点图上。对 R 来说非常新,使用 ggplot2 并成功绘制了原始数据和移动平均线,但难以添加标准偏差。有什么建议吗?谢谢

    Mar<- ggplot(NG_data2,
       mapping = aes(x = Varve,
                     y = Aragonite))+
      geom_line(size = 1, colour = "black")+
      geom_ma(mapping = NULL,
          data = NG_data2,
          position = "identity",
          show.legend = NA,
          inherit.aes = TRUE,
          ma_fun = SMA,
          n = 30,
          wilder = FALSE,
          ratio = NULL,
          v = 1,
          wts = 3,
          colour = "red")

【问题讨论】:

    标签: r ggplot2 scatter-plot moving-average standard-deviation


    【解决方案1】:

    我不知道目前是否可以从 tidyquant 获得标准偏差,就像它做移动平均的方式一样,但应该可以用其他方式计算这些,并将它们输入 ggplot。例如,滚动平均值和 sd 可以使用 slider 包和 dplyr 计算,如下所示:

    library(dplyr); library(slider); library(lubridate)
    
    #storms is a dataset that comes with dplyr. Here I grab a piece from one storm:
    storms[storms$name == "Frederic",1:10] %>%
    
      # here I use lubridate::ymd to create timestamps combining a few columns; 
      #  won't be needed if your data already has a date column
      mutate(time = ymd_h(paste(year, month, day, hour))) %>%
    
      # here's the guts: slider::slide_inded_dbl takes a variable, an indexing
      #  column (time here), a function (mean or sd), and an index window
      mutate(ma = slide_index_dbl(wind, time, mean, .before = days(2)),
             sd = slide_index_dbl(wind, time, sd, .before = days(2))) %>%
    
      ggplot(aes(x = time, y = wind)) +
      geom_line() +
      geom_line(aes(y = ma), lty = "dotted") +
      geom_ribbon(aes(ymin = ma - sd, ymax = ma + sd), alpha = 0.1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-22
      • 1970-01-01
      • 2018-03-08
      • 2018-02-25
      • 2023-04-09
      • 2018-03-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多