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

时间:2016-08-08 22:51:13

标签: r plotly

非常不言自明。如果调用颜色参数,则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)

enter image description here 这有点类似于a previous question,但这看起来有些黑客可能很难在这里应用

TIA

1 个答案:

答案 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 = namecategoryorder = "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