2016-09-07 90 views
0

我想繪製水平條並通過正值/負值對它們進行着色。問題是,即使我使用了categoryarray = cat,酒吧的順序也發生了變化。如果我刪除color = sign部分,訂單是好的。這是我到目前爲止的代碼:分類在垂直條形圖中的順序(在Plotly中)

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

回答

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 

enter image description here