Search code examples
rdplyrplotlybar-chartr-plotly

Plot Plotly Values in Ascending Order


I have a dataset, data, with the following values:

   ID                TIME                         Duration   
    A                12/18/2019 4:45:10 AM        1 sec
    A                12/18/2019 9:06:59 PM        0 sec                    
    B                12/19/2019 4:14:13 AM        7 sec
    B                12/19/2019 4:14:20 AM        0 sec
    A                12/18/2019 4:45:11 AM        0 sec
 p <- plot_ly(data = df,
        x = ~ID,
        y = ~Duration,
        name = "Title",
        type = "bar",
        orientation = 'v',
        order = "ascending"

     )%>% 
layout(
       title = "Title",
       xaxis = list(title = "ID", tickangle = -45 ),
       yaxis = list(title = "Time In Seconds"))

How would I specify that the graph is in ascending order like the picture below. categoryorder = 'ascending" is not working.

enter image description here


Solution

  • We can use reorder to set the levels of ID which is a factor to be set based on Duration values.

    library(plotly)
    library(dplyr)
    
    df1 %>% 
      group_by(ID) %>% 
      mutate(Dur.order = sum(as.numeric(Duration))) %>% 
      ungroup() %>% 
      mutate(ID.order = reorder(ID, Dur.order)) %>% 
    plot_ly(data = .,
                 x = ~ID.order,
                 y = ~Duration,
                 name = "Title",
                 type = "bar",
                 orientation = 'v',
                 order = "ascending") %>% 
      layout(title = "Title",
             xaxis = list(title = "ID", tickangle = -45 ),
             yaxis = list(title = "Time In Seconds"))
    

    Data:

    df1 <- structure(list(ID = c("A", "A", "B", "B", "A"), 
                          Date = c("12/18/2019 4:45:10 AM", "12/18/2019 9:06:59 PM", 
                                   "12/19/2019 4:14:13 AM", "12/19/2019 4:14:20 AM", 
                                   "12/18/2019 4:45:11 AM"), 
                          Duration = structure(c(1, 0, 7,0 , 0), 
                     class = "difftime", units = "secs")), 
                     row.names = c(NA, -5L), class = "data.frame")