Search code examples
rplotlydata-visualization

Forcing Barplots to be in the Same Order as the Dataframe


When making barplots with the plotly library in R - for example:

library(plotly)

Animals <- c("giraffes", "orangutans", "monkeys")
SF_Zoo <- c(20, 14, 23)
LA_Zoo <- c(12, 18, 29)
data <- data.frame(Animals, SF_Zoo, LA_Zoo)

fig <- plot_ly(data, x = ~Animals, y = ~SF_Zoo, type = 'bar', name = 'SF Zoo')
fig <- fig %>% add_trace(y = ~LA_Zoo, name = 'LA Zoo')
fig <- fig %>% layout(yaxis = list(title = 'Count'), barmode = 'group')

I have often noticed that the order of the bars won't be in the same order as the order that the rows appear in the original data frame.

Reading some posts on stackoverflow (e.g. Ordering in r plotly barchart), I see that there are some methods to correct for this problem. However, all these methods seem to involve manually re-ordering the rows. I have many rows and it would take a long time to manually re-order them.

  • Is there really no other way to "force" plotly to make the barplots appear in the same order as the data frame itself?

Thank you!


Solution

  • So I just used unique() to create a vector of possible values in the order that they appear in the original data and then I combined your code with the this guy's answer in the post you linked: https://stackoverflow.com/a/40149759/16502170

    It's still somewhat of a workaround, but it's a lot faster than manually typing things out in the order you want.

    library(plotly)
    
    Animals <- c("giraffes", "orangutans", "monkeys")
    SF_Zoo <- c(20, 14, 23)
    LA_Zoo <- c(12, 18, 29)
    data <- data.frame(Animals, SF_Zoo, LA_Zoo)
    
    xform <- list(categoryorder = "array",
                  categoryarray = unique(Animals))
    
    fig <- plot_ly(
      x = ~Animals, y = ~SF_Zoo,
      name = 'SF Zoo',
      type = "bar") %>% 
      layout(xaxis = xform)
    
    
    fig <- fig %>% add_trace(y = ~LA_Zoo, name = 'LA Zoo')
    fig <- fig %>% layout(yaxis = list(title = 'Count'), barmode = 'group')
    
    fig