2017-08-25 65 views
0

嗨,Plotly - 訂購和着色由因子變量和條形圖

我使用plotly產生有序的條形圖,這將顯示上的X軸和頻率計數的客戶羣Y軸。 問題是,我也想根據細分的頻率設置顏色。

我使用一個數據幀93周的觀察具有相同的結構,因爲這:

df <- data.frame(
     Segments = c("Pete", "Gary", "TopNews"...), 
     Frequency = c(4,2,5...) 
     ) 

問題

正如預期的那樣,R自動識別爲一個因素的「段」變量。當我第一次繪製圖表時,它自己命令(如預期的那樣)。我用下面的代碼:

plot_ly(Segments2, y = ~Var1, x = ~Freq, type = "bar", orientation = 'h') 

所以這不是一個問題,但是當我試圖酒吧的領帶顏色的「頻率」變量就成爲一個問題,即:

plot_ly(Segments2, y = ~Var1, x = ~Freq, type = "bar", color = ~Freq, orientation = 'h') 

當然,R打印以下錯誤:

‘range’ not meaningful for factors 

所以,這一切的一切,我的問題是:我怎麼顏色,有序plotly條形圖使用頻率順序顏色?

enter image description here

回答

1

你可以添加你的頻率與對象color

enter image description here

library(plotly) 

df <- data.frame(
    Segments = c("Pete", "Gary", "TopNews", "Harry"), 
    Freq = c(4,2,5,3) 
) 

plot_ly(df, 
     y = ~Segments, 
     x = ~Freq, 
     type = "bar", 
     orientation = 'h', 
     marker = list(color = df$Freq, 
         showscale=T) 
     )