我正在尝试绘制水平条,并按正/负值对其进行着色。问题是即使我使用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
答案 0 :(得分:1)
由于您使用的是水平方向,因此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