【问题标题】:matplotlib scatter plot using a 3rd data series to designate colormatplotlib 散点图使用第三个数据系列来指定颜色
【发布时间】:2019-11-14 16:53:54
【问题描述】:

我有 3 个共享相同索引值的数据系列:

系列a
0.6
B 0.4
C 0.7
D 0.5

b 系列
0.8
B 0.4
C 0.7
D 0.5

c 系列
10
B 23
C 50
D 100

a 和 b 系列是我的 x 和 y 轴。我想使用 c 系列来指定点的颜色(如果 c > 80 时的值,则颜色 = c > 20 时的红色 elif 值,然后颜色 = 蓝色)。

这是我的代码到目前为止的样子:

colors = 'black'  #default color
plt.scatter(a, b, s=np.pi*1, c=colors, alpha=0.5)
    #this is what I'm looking for
    #if value at c > 80 then colors = red elif value at c > 20 then colors = blue
plt.show()

这是完成的图表的样子:

谢谢!

【问题讨论】:

    标签: pandas matplotlib


    【解决方案1】:

    您希望np.select 定义颜色:

    colors = np.select((c>80, c>20), ('r','b'), default='g')
    plt.scatter(a,b, c=colors)
    

    输出:

    【讨论】:

      【解决方案2】:

      另一种方式,但不如@quang-hoang 的简洁。

      使用您的条件创建一个函数,然后将其apply 发送到df

      def colors(row):
          if row.v > 80: return 'red'
          elif row.v > 20: return 'blue' 
          else: return 'green'
      
      df['colors'] = df.apply(colors, axis=1)
      

      给你这个:

           x    y      v colors
      A  0.6  0.8   10.0  green
      B  0.4  0.4   23.0   blue
      C  0.7  0.7   50.0   blue
      D  0.5  0.5  100.0    red
      
      df.plot.scatter('x', 'y', c=df.colors)
      

      【讨论】:

        猜你喜欢
        • 2012-01-02
        • 2016-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-23
        • 2014-09-10
        相关资源
        最近更新 更多