R Plotly Stacked Bar突破日期顺序不正确

R Plotly Stacked Bar breakout date not in correct order

我有一个 R 绘图堆叠条形图,其中按日期细分。我正在尝试将顺序从最旧的日期 10/1/2020 更改为最上面的最新日期 01/01/2021。我注意到在当前状态下,它甚至没有按正确的日期顺序排列。数据框以正确的顺序显示。

我目前的代码。

 ramp2 <- colorRamp(c("deepskyblue4", "white"))
 ramp.list2 <- rgb( ramp2(seq(0, 1, length = 15)), max = 255)
 plot_ly(pcd_2,
         x = ~reorder(u_reason_code,-total_qty, sum), y = ~total_qty, type = 'bar', color = ~month_breakout ) %>%
   layout(list(title = 'Cost'), barmode = 'stack') %>%
   layout(colorway = ramp.list2) %>%
   config(displayModeBar = FALSE)

尝试将您的日期格式化为下一个代码的因素(未测试,因为没有共享数据):

#Process data
pcd_2$Date <- as.Date(pcd_2$month_breakout,'%m/%d/%Y')
pcd_2 <- pcd_2[order(pcd_2$Date),]
pcd_2$month_breakout <- factor(pcd_2$month_breakout,
                               levels = unique(pcd_2$month_breakout),
                               ordered = T)
#Plot
ramp2 <- colorRamp(c("deepskyblue4", "white"))
ramp.list2 <- rgb( ramp2(seq(0, 1, length = 15)), max = 255)
plot_ly(pcd_2,
        x = ~reorder(u_reason_code,-total_qty, sum), y = ~total_qty, type = 'bar', color = ~month_breakout ) %>%
  layout(list(title = 'Cost'), barmode = 'stack') %>%
  layout(colorway = ramp.list2) %>%
  config(displayModeBar = FALSE)