我正在尝试绘制水平条并按正/负值对它们进行着色。问题是,即使我使用了categoryarray = cat,条形图的顺序也发生了变化。如果我删除 color = sign
部分,则顺序没问题。这是到目前为止我的代码:
library(plotly)
library(data.table)
dt <- data.table( cat = c("A", "B", "C", "D"),
val = c(12, -3, -9, 2))
dt[, sign := "p"]
dt[val < 0 , sign := "n"]
setorder(dt, -cat)
p <- plot_ly(data = dt, y = cat, x = val, type = "bar", orientation = "h", color = sign ) %>%
layout(title = "Some title",
xaxis = list(categoryarray = cat, categoryorder = "array"),
showlegend = FALSE)
p
最佳答案
由于您使用的是水平方向,因此 y 轴包含类别。因此,您需要做的是在 layout
函数内编辑 y 轴:
library(plotly)
library(data.table)
dt <- data.table( cat = c("A", "B", "C", "D"),
val = c(12, -3, -9, 2))
dt[, sign := "p"]
dt[val < 0 , sign := "n"]
setorder(dt, -cat)
p <- plot_ly(data = dt, y = cat, x = val, type = "bar", orientation = "h", color = sign) %>%
layout(title = "Some title",
yaxis = list(categoryarray = cat, categoryorder = "array"),
showlegend = FALSE)
p
关于r - 垂直条形图中的类别顺序(在 Plotly 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39368599/