简体   繁体   中英

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")

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM