Reputation: 1381
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
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") )
)
)
Upvotes: 1