如何在带有颜色变量的 R Plotly 条形图中保留所需的顺序

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

不言而喻。如果调用颜色参数,则 x 轴上的值排序不正确

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)

这与 有点相似,但似乎有点难以在这里应用

TIA

更新:plotly_4.5.6 包含一些更改(水平线下方的原始答案)

我原来的答案可以修改为:

p <- plot_ly(data = df, x = ~names, y = ~count, type = "bar", color = ~type)
p <- layout(p, xaxis = list(categoryarray = ~names, categoryorder = "array"))
p

您可以利用对 plotly 所做的更改(阅读更多 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")

原答案

使用 layout 和您可以提供给 xaxis 的参数。具体来说,您要设置 categoryarray = namecategoryorder = "array"。来自 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