Reputation: 3505
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")
plot_ly(data=df,x=names,y=count,type="bar",
color = type)
This is somewhat similar to a previous question but that seemed a bit of a hack that may be difficult to apply here anyways
TIA
Upvotes: 2
Views: 9226
Reputation: 17611
Update: plotly_4.5.6 included some changes (original answer below the horizontal rule)
My original answer could be modified to:
p <- plot_ly(data = df, x = ~names, y = ~count, type = "bar", color = ~type)
p <- layout(p, xaxis = list(categoryarray = ~names, categoryorder = "array"))
p
Or
You can take advantage of changes made to plotly (read more here):
Also, the order of categories on a discrete axis, by default, is now either alphabetical (for character strings) or matches the ordering of factor levels.
# set the factor order however you want
df$names <- factor(df$names,
levels = c("I", "want", "this", "order"))
# plot it (note, plotly can now infer the trace, but I specified as "bar" anyway
plot_ly(data = df, x = ~names, y = ~count, color = ~type, type = "bar")
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 https://plot.ly/r/reference/:
Set
categoryorder
to "array" to derive the ordering from the attributecategoryarray
.
p <- plot_ly(data=df, x=names, y=count, type="bar", color = type)
p <- layout(p, xaxis = list(categoryarray = names, categoryorder = "array"))
p
Upvotes: 14