Black Lives Matter. Please consider donating to Black Girls Code today.

Category Order for Barplot - Weird behavior, possibly bug

Hi

For a project I need to create bar plots in which the bars can be ordered decreasing by value. This was done using the xaxis-options with categoryorder = “array”, categoryarray = myOrderedLabels. This approach provided most flexibility for including other types of orderings.

I found a rather weird and unexpected behavior with these plots, apparently caused by one label being “-1”. In some cases, when ordering decreasing by value the order seems to be reversed, even though the categoryarray is ordered correctly. You can find a minimal example using some random data. If you run it multiple times, you will find that the bars are sometimes ordered decreasing and sometimes ordered increasing.

I am not sure if this issue occurs during the translation from R to the plotly.js library or it is a bug in plotly.js. Maybe one of the plotly devs could look into that?

Thanks a lot for your input!

Cheers
Chris

library(plotly)

labels <- c("-2", 1:10)
values <- runif(11, 0, 100)

data <- data.frame(labels, values)

# Ordered by values
categoryOrder <- as.vector(data[order(data[["values"]], decreasing = TRUE),"labels"])
print(categoryOrder)

p <- plot_ly(data)
p <- add_trace(p, x = data[["labels"]], y = data[["values"]], type = 'bar')
p <- layout(p, yaxis = list(title = "values"), xaxis = list(title = "labels", type="category", categoryorder = "array", categoryarray = categoryOrder))
p