Search code examples
rplotlystacked-chartbreakout

R Plotly Stacked Bar breakout date not in correct order


I have an R plotly stacked bar chart where it's broken out by date. I am trying to change the order from the oldest date 10/1/2020 to the newest date 01/01/2021 on top. I noticed in the current state that it's not even in the correct order of dates. The data frame shows in the correct order.

The current code I have.

 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)

enter image description here

enter image description here


Solution

  • Try formating your date as factor with next code (not tested as no data was shared):

    #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)