r - 垂直条形图中的类别顺序(在 Plotly 中)

标签 r plotly

我正在尝试绘制水平条并按正/负值对它们进行着色。问题是,即使我使用了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

输出: enter image description here

最佳答案

由于您使用的是水平方向,因此 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

enter image description here

关于r - 垂直条形图中的类别顺序(在 Plotly 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39368599/

相关文章:

用字符串替换列表中找到的字符串

python - 如何使用 Dash plotly 添加/创建自定义加载程序?

python - 在 Google Colab 中使用 plotly 绘制超过 600 万行的数据集

r - 如何进行矩阵计算以获得变量的叉积

r - 使用knitr编译成pdf时如何控制输出宽度?

r - 如何使用 R sf 包从底层网格裁剪多边形?

R:创建名称来自变量的新列

python - Plotly:如何使用文本模板的空间来自动化 y 轴?

python - 在 pycharm 上使用 plotly 时出错

python - 不显示折线图范围划分以排除 python 中的非工作时间和周末