pssguy pssguy - 1 year ago 124
R Question

How can I retain desired order in R Plotly bar chart with color variable

Pretty self-evident. Values on x-axis are not ordered correctly if color parameter is invoked

df <- structure(list(count = c(8, 3, 5, 9), names = c("I", "want",
"this", "order"), type = c("H", "A", "H", "A")), .Names = c("count",
"names", "type"), row.names = c(NA, -4L), class = "data.frame")

color = type)

enter image description here
This is somewhat similar to a previous question but that seemed a bit of a hack that may be difficult to apply here anyways


Answer Source

Use layout and the arguments you can feed to xaxis. Specifically, you want to set categoryarray = name and categoryorder = "array". From the layout section of

Set categoryorder to "array" to derive the ordering from the attribute categoryarray.

p <- plot_ly(data=df, x=names, y=count, type="bar", color = type)
p <- layout(p, xaxis = list(categoryarray = names, categoryorder = "array"))