簡體   English   中英

ggplot2 將滾動平均值的標准差添加到散點圖

[英]ggplot2 adding standard deviation of rolling mean to scatter graph

我正在努力將滾動平均值的標准偏差映射到散點圖上。 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")

我不知道目前是否有可能從tidyquant獲得標准偏差,就像它做移動平均的方式一樣,但應該可以用其他方式計算這些,並將它們輸入 ggplot。 例如,滾動平均值和 sd 可以使用slider package 和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)

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM