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")
Original Answer
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
attribute categoryarray
.
p <- plot_ly(data=df, x=names, y=count, type="bar", color = type)
p <- layout(p, xaxis = list(categoryarray = names, categoryorder = "array"))
p