BogdanC BogdanC - 2 months ago 60
R Question

Categories order in vertical bar chart ( in Plotly )

I am trying to plot horizontal bars and color them by positive / negative values. The issue is that the order of the bar is changed even though I used

categoryarray = cat
. If I remove the
color = sign
part, the order is fine. Here is my code so far:

library(plotly)
library(data.table)

dt <- data.table( cat = c("A", "B", "C", "D"),
val = c(12, -3, -9, 2))
dt[, sign := "p"]
dt[val < 0 , sign := "n"]
setorder(dt, -cat)

p <- plot_ly(data = dt, y = cat, x = val, type = "bar", orientation = "h", color = sign ) %>%
layout(title = "Some title",
xaxis = list(categoryarray = cat, categoryorder = "array"),
showlegend = FALSE)
p


And the output:
enter image description here

Answer

Since you are using the horizontal orientation, the y-axis carries the categories. So what you need to do is to edit the y-axis inside the layout function instead:

library(plotly)
library(data.table)

dt <- data.table( cat = c("A", "B", "C", "D"),
                  val = c(12, -3, -9, 2))
dt[, sign := "p"]
dt[val < 0 , sign := "n"]
setorder(dt, -cat)

p <- plot_ly(data = dt, y = cat, x = val, type = "bar",  orientation = "h", color = sign) %>%
  layout(title = "Some title",
         yaxis = list(categoryarray = cat, categoryorder = "array"),
         showlegend = FALSE)
p

enter image description here

Comments