按月汇总不同年份并在 x 轴上创建带有月份的绘图条

Aggregate by month for different years and create plotly bar with months in x-axis

我有以下数据框:

Week<-structure(c(18323, 18330, 18337, 18344, 18351, 18358, 18365, 
18372, 18379, 18386, 18393, 18400, 18407, 18414, 18421, 18428, 
18435, 18442, 18449, 18456, 18463, 18470, 18477, 18484, 18491, 
18498, 18505, 18512, 18519, 18526, 18533, 18540, 18547, 18554, 
18561, 18568, 18575, 18582, 18589, 18596, 18603, 18610, 18617, 
18624, 18631, 18638, 18645, 18652, 18659, 18666, 18673, 18680, 
18687, 18694, 18701, 18708, 18715, 18722, NA), class = "Date")

First<-c(NA, 12, 28, 89, 205, 311, 367, 419, 536, 673, 787, 996, 1501, 
2091, 2836, 3971, 5429, 7422, 9653, 12205, 15096, 19962, 23567, 
28432, 33051, 37347, 43390, 49897, 54851, 60913, 67073, 72769, 
79629, 84063, 88398, 89579, 88464, 85595, 81697, 74943, 67632, 
58226, 53371, 49759, 51508, 55515, 58813, 62240, 62627, 62646, 
61285, 54438, 49614, 46721, 44554, 48151, 54014, 68891, 47176
)
Second<-c(NA, 12, 28, 89, 205, 311, 367, 419, 536, 673, 787, 996, 1501, 
2091, 2836, 3971, 5429, 7422, 9653, 12205, 15096, 19962, 23567, 
28432, 33051, 37347, 43390, 49897, 54851, 60913, 67073, 72769, 
79629, 84063, 88398, 89579, 88464, 85595, 81697, 74943, 67632, 
58226, 53371, 49759, 51508, 55515, 58813, 62240, 62627, 62646, 
61285, 54438, 49614, 46721, 44554, 48151, 54014, 68891, 47176
)


re<-data.frame(Week,First,Second)

我想按月求和,但我有 2 年 20202021 所以我需要将每年的月份分开

library(lubridate)
bymonth <- aggregate(cbind(First)~month(Week),
                     data=re,FUN=sum)

然后我需要创建一个 plotly 条形图,但月份显示不正确。

p <- plot_ly() %>% 
      add_bars(bymonth, x = ~Month, y = bymonth[,2], name = "fIRST", 
               marker = list(color = "#3E5B84")
               )

您可以从日期中提取年月,汇总并绘制 -

library(dplyr)
library(plotly)

re %>%
  arrange(Week) %>%
  mutate(month_year = format(Week, '%Y-%b'), 
         month_year = factor(month_year, unique(month_year))) %>%
  group_by(month_year) %>%
  summarise(First = sum(First, na.rm = TRUE)) %>%
  plot_ly() %>% 
  add_bars(x = ~month_year, y = ~First, 
           marker = list(color = "#3E5B84"))