Michael
Michael

Reputation: 1381

Sort plotly vertical bar chart by frequency

I want to sort a vertical bar chart based on the level of the quantitative variable on the x-axis.

Reproducible example:

library(plotly)
library(dplyr)

df <- data.frame(a = c(1000,100,500,1), b = c('blue', 'green', 'yellow', 'red'))

plot_ly(
    data = df,
    x = ~a,
    y = ~b,
    type = 'bar',
    orientation = 'h'
) %>%
    layout(
        yaxis = list(
            categoryorder = "array",
            categoryarray = ~a
            )
        )

So I want a vertical bar chart where the ordering on the y-axis downwards is: 'blue', 'yellow', 'green' and 'red'. I read about categoryorder, which seemed a good solution, but somehow it's not working in practice.

Upvotes: 2

Views: 2486

Answers (1)

Florian
Florian

Reputation: 25375

Option 1

library(plotly)
library(dplyr)

df <- data.frame(a = c(1000,100,500,1), b = c('blue', 'green', 'yellow', 'red'))
df$b = factor(df$b,levels =c("red","green","yellow", "blue") )

plot_ly(
  data = df,
  x = ~a,
  y = ~b,
  type = 'bar',
  orientation = 'h'
) 

Option 2

library(plotly)
library(dplyr)

df <- data.frame(a = c(1000,100,500,1), b = c('blue', 'green', 'yellow', 'red'))

plot_ly(
  data = df,
  x = ~a,
  y = ~b,
  type = 'bar',
  orientation = 'h'
) %>%
  layout(
    yaxis = list(
      categoryorder = "array",
      categoryarray = ~c("red","green","yellow", "blue") )
    )
  )

Hope this helps! enter image description here

Upvotes: 1

Related Questions