ggplot2将滚动平均值的标准差添加到散点图
Posted
技术标签:
【中文标题】ggplot2将滚动平均值的标准差添加到散点图【英文标题】:ggplot2 adding standard deviation of rolling mean to scatter graph 【发布时间】: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")
【问题讨论】:
【参考方案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)
【讨论】:
以上是关于ggplot2将滚动平均值的标准差添加到散点图的主要内容,如果未能解决你的问题,请参考以下文章
R语言使用ggplot2包的快速可视化函数qplot绘制散点图(添加平滑曲线与标准差带)实战
R语言使用ggplot2包geom_jitter()函数绘制分组(strip plot,一维散点图)带状图(添加均值标准偏差)实战
R语言使用ggplot2包geom_jitter()函数绘制分组(strip plot,一维散点图)带状图(编写自定义函数添加均值标准偏差)实战