简体   繁体   English

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

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

Pretty self-evident. 不言而喻。 Values on x-axis are not ordered correctly if color parameter is invoked 如果调用了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)

在此处输入图片说明 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 TIA

Update: plotly_4.5.6 included some changes (original answer below the horizontal rule) 更新:plotly_4.5.6进行了一些更改(水平规则下方的原始答案)

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 ): 您可以利用对plotly所做的更改( 在此处了解更多信息 ):

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 . 使用layout和您可以提供给xaxis的参数。 Specifically, you want to set categoryarray = name and categoryorder = "array" . 具体来说,您要设置categoryarray = namecategoryorder = "array" From the layout section of https://plot.ly/r/reference/ : https://plot.ly/r/reference/的布局部分:

Set categoryorder to "array" to derive the ordering from the attribute categoryarray . 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM