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

pss*_*guy 1 r plotly

不言而喻。如果调用了color参数,则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)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明 这与先前的问题有点类似,但似乎有点骇人之处,无论如何都很难在这里应用

TIA

Jot*_*ota 6

更新: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
Run Code Online (Sandbox Code Playgroud)

要么

您可以利用对plotly所做的更改(在此处了解更多信息):

同样,默认情况下,离散轴上类别的顺序现在默认为字母顺序(对于字符串)或与因子级别的顺序匹配。

# 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")
Run Code Online (Sandbox Code Playgroud)

原始答案

使用layout和您可以提供的参数xaxis。具体来说,您要设置categoryarray = namecategoryorder = "array"。从https://plot.ly/r/reference/的布局部分:

设置categoryorder为“ array”可以从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
Run Code Online (Sandbox Code Playgroud)