2

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)

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

TIA

Community
  • 1
  • 1
pssguy
  • 3,455
  • 7
  • 38
  • 68

1 Answers1

13

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
Jota
  • 17,281
  • 7
  • 63
  • 93
  • #Jota. Thanks for answer(which works) and reference link. Looking at the reference , I'm still not sure why it needs this layout line at all as "By default, plotly uses "trace", which specifies the order that is present in the data supplied" and the dataframe names order is "I","want","this","order"?? – pssguy Aug 09 '16 at 03:13
  • @pssguy I agree with you that it is confusing. Not sure, but I am guessing that if it's not a bug, "the data supplied" could mean the data as supplied in the html file: `"data":[{"type":"bar","inherit":false,"x":["I","this"],"y":[8,5],"name":"H","marker":{"color":"#66C2A5"}},{"type":"bar","inherit":false,"x":["want","order"],"y":[3,9],"name":"A","marker":{"color":"#8DA0CB"}}]` and not the data supplied as input. – Jota Aug 09 '16 at 04:19
  • @jota I think it's worth mentioning that there is a breaking change in plotly 4.0 as described here http://moderndata.plot.ly/upgrading-to-plotly-4-0-and-above/ – Charlie Joey Hadley Nov 14 '16 at 12:53