问题描述
我使用const reverseMap = (arg,fn) => arg.map((_,i,arr) => fn(arr[arr.length - 1 - i]))
// Or
function reverseMap(arg,fn) {
return arg.map((_,arr) => fn(arr[arr.length - i - 1]))
}
和ggplot
创建了一个图。我的数据集中有两个变量,我想添加其中一个变量(在这种情况下为plotly
)的12个月移动平均值。我相信headline inflation
不支持geom_ma
,因此我正在寻找一种适用于plotly
plotly
编辑-我将自己的数据集从长格式更改为宽格式,并分别运行每个p1 <- ggplot(inflation,aes(Date)) +
geom_line(aes(y=`Core Inflation`,col = '#75002B'),size = 1.5) +
geom_line(aes(y=`Headline Inflation`,col = '#EFBE93'),size = 1.5) +
geom_ma(aes(y = `Headline Inflation`,col = '#BD215B'),ma_fun = SMA,n=12,size=1.5) +
theme_bw() +
labs(y='Annual Inflation Rate (%)',color = "") +
scale_color_manual(values = c("#75002B",'#BD215B',"#EFBE93"),labels = c('Core','MA','Headline'))
p1 %>% ggplotly()
,因为我很难在{{1}上运行geom_line
}当我的数据为长格式时。
geom_ma
编辑-我设法在headline inflation
中制作了情节,但是当我在structure(list(Date = structure(c(16983,17014,17045,17075,17106,17136,17167,17198,17226,17257,17287,17318,17348,17379,17410,17440,17471,17501,17532,17563,17591,17622,17652,17683,17713,17744,17775,17805,17836,17866,17897,17928,17956,17987,18017,18048,18078,18109,18140,18170,18201,18231,18262,18293,18322,18353,18383,18414,18444
),class = "Date"),`Headline Inflation` = c(6.99,6.83,6.9,7.26,7.34,7.3,8.2,7.75,7.05,6.68,6.28,6.08,5.45,5.37,5.57,5.16,5.18,5.17,3.56,3.52,3.51,3.58,3.84,3.96,4.46,4.41,4.79,5.12,5.56,5.15,4.66,4.42,4.5,4.53,4.08,3.94,3.64,3.71,2.93,3.02,2.46,2.59,2.05,2.45,2.35,1.64,2.06,2.15,2.09),`Core Inflation` = c(6.24,6.13,6.36,6.77,6.75,7.84,7.65,7.13,6.96,6.61,6.63,6.34,6.38,6.2,5.83,5.81,5.51,3.55,3.49,3.48,3.41,3.65,3.38,3.95,4.1,4.25,4.21,4.27,4.39,3.89,3.85,3.7,2.77,3.18,2.84,2.85,1.63,1.74,1.67,1.22,2.43,2.86
)),row.names = c(NA,-49L),class = c("tbl_df","tbl","data.frame"
))
中运行时,我得到一个错误,指出ggplot2
是ggplotly
geom_ma
解决方法
Since,geom_ma
is not implemented in plotly
yet。您可以使用现有功能来计算移动平均线。我正在使用zoo::rollapplyr
,其功能为mean
。
library(tidyverse)
p1 <- inflation %>%
mutate(moving_avg = zoo::rollapplyr(`Headline Inflation`,2,mean,partial = TRUE)) %>%
pivot_longer(cols = -Date) %>%
ggplot() + aes(Date,y = value,color = name) +
geom_line(size = 1.5) +
theme_bw() +
labs(y='Annual Inflation Rate (%)',color = "") +
scale_color_manual(values = c("#75002B",'#BD215B',"#EFBE93"),labels = c('Core','MA','Headline'))
p1
请注意,还有zoo::rollmeanr
默认情况下使用mean
,但缺少partial = TRUE
参数,因此它返回前12个值作为NA
。