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

如何在带有颜色变量的R Plotly条形图中保持所需的顺序,r,plotly,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轴上的值顺序不正确

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)

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

#佐塔。谢谢你的回答(有效)和参考链接。查看引用,我仍然不确定为什么它需要这个布局行,因为“默认情况下,绘图使用“trace”,它指定了所提供数据中存在的顺序”,而数据帧名称顺序是“I”、“want”、“this”、“order”?@pssgue我同意你的说法,这是令人困惑的。不确定,但我猜如果它不是一个bug,“提供的数据”可能意味着html文件中提供的数据:
“数据”:[{“类型”:“bar”,“继承”:false,“x”:[“I”,“this”],“y”:[8,5],“name”:“H”,“marker”:{“color”:“#66C2A5”},{“type”:“bar”,“继承”:false,“x”:[“want”,“order”],“y”:[3,9],“name”:“a”,“marker”:“{“color”:“358c2; da0cb
而不是作为输入提供的数据。@jota我认为值得一提的是,plotly 4.0中有一个突破性的变化,如下所述
# 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")
p <- plot_ly(data=df, x=names, y=count, type="bar", color = type)
p <- layout(p, xaxis = list(categoryarray = names, categoryorder = "array"))
p