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

假如想象 提交于 2020-01-03 01:35:14

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/38839657/how-can-i-retain-desired-order-in-r-plotly-bar-chart-with-color-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!