2017-08-25 36 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) 
     )