代码之家  ›  专栏  ›  技术社区  ›  Pryore

按因子变量和条形图进行绘图排序和着色

  •  0
  • Pryore  · 技术社区  · 7 年前

    我正在使用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')
    

    ‘range’ not meaningful for factors
    

    enter image description here

    1 回复  |  直到 7 年前
        1
  •  2
  •   Maximilian Peters    7 年前

    您可以将频率添加到 color marker 对象

    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)
            )