非常不言自明。如果调用颜色参数,则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)
这有点类似于a previous question,但这看起来有些黑客可能很难在这里应用
TIA
答案 0 :(得分:4)
更新: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
或
您可以利用对情节的更改(阅读更多here):
此外,默认情况下,离散轴上的类别顺序现在是 按字母顺序排列(用于字符串)或匹配排序 因子水平。
# 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 = name
和categoryorder = "array"
。从https://plot.ly/r/reference/的布局部分:
将
categoryorder
设置为“array”以从中导出排序 属性categoryarray
。
p <- plot_ly(data=df, x=names, y=count, type="bar", color = type)
p <- layout(p, xaxis = list(categoryarray = names, categoryorder = "array"))
p