gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 08:23:36 25 4
gpt4 key购买 nike

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

最佳答案

更新: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

关于r - 如何在带有颜色变量的 R Plotly 条形图中保留所需的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38839657/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com