2017-07-24 82 views
1

我想根據x軸上的定量變量的水平對垂直條形圖進行排序。按頻率對圖表進行垂直條形圖排序

重複的例子:

library(plotly) 
library(dplyr) 

df <- data.frame(a = c(1000,100,500,1), b = c('blue', 'green', 'yellow', 'red')) 

plot_ly(
    data = df, 
    x = ~a, 
    y = ~b, 
    type = 'bar', 
    orientation = 'h' 
) %>% 
    layout(
     yaxis = list(
      categoryorder = "array", 
      categoryarray = ~a 
      ) 
     ) 

所以我希望有一個垂直條形圖,其中在y軸的順序向下是:「藍色」,「黃色」,「綠色」和「紅色」。我閱讀了關於類別訂單,這似乎是一個很好的解決方案,但不知何故它不是在實踐中工作。

回答

0

選項1

library(plotly) 
library(dplyr) 

df <- data.frame(a = c(1000,100,500,1), b = c('blue', 'green', 'yellow', 'red')) 
df$b = factor(df$b,levels =c("red","green","yellow", "blue")) 

plot_ly(
    data = df, 
    x = ~a, 
    y = ~b, 
    type = 'bar', 
    orientation = 'h' 
) 

選項2

library(plotly) 
library(dplyr) 

df <- data.frame(a = c(1000,100,500,1), b = c('blue', 'green', 'yellow', 'red')) 

plot_ly(
    data = df, 
    x = ~a, 
    y = ~b, 
    type = 'bar', 
    orientation = 'h' 
) %>% 
    layout(
    yaxis = list(
     categoryorder = "array", 
     categoryarray = ~c("red","green","yellow", "blue")) 
    ) 
) 

希望這有助於! enter image description here

+0

感謝您的答覆,我希望是這樣做沒有任何因子水平搞亂,並直接在'plot_ly()'函數 – Michael

+0

那也是有可能做到這一點,補充說,第二個選項,我的答案。請接受/ upvote我的答案,如果你發現它有幫助,謝謝! – Florian