【问题标题】:Get color of a scatter point获取散点的颜色
【发布时间】:2018-06-03 03:43:16
【问题描述】:

我有一个带有一些玩具数据的散点图。

我想在给定点旁边用点的颜色绘制一个标签。

玩具示例:

x = 100*np.random.rand(5,1)
y = 100*np.random.rand(5,1)
c = np.random.rand(5,1)

fig, ax = plt.subplots()
sc = plt.scatter(x, y, c=c, cmap='viridis')

# I want to annotate the third point (idx=2)
idx = 2  
ax.annotate("hello", xy=(x[idx],y[idx]), color='green', 
            xytext=(5,5), textcoords="offset points")
plt.show()

我需要以某种方式获得这一点的颜色并将我的 color='green' 部分更改为 color=color_of_the_point

如何获取散点图中某个点的颜色?

颜色向量c被转换为颜色图,还可以进行进一步的修改,例如归一化或alpha值。

sc 有一个检索点坐标的方法:

sc.get_offsets()

所以也有一种方法来获取点的颜色是合乎逻辑的,但我找不到这样的方法。

【问题讨论】:

    标签: python matplotlib scatter-plot


    【解决方案1】:

    散点图是PathCollection,它是ScalarMappable 的子类。 ScalarMappable 有一个方法 to_rgba。这可以用来获取colorvalues对应的颜色。

    在这种情况下

    sc.to_rgba(c[idx])
    

    请注意,问题中使用的数组是二维数组,这通常是不受欢迎的。所以一个完整的例子看起来像

    import matplotlib.pyplot as plt
    import numpy as np
    
    x = 100*np.random.rand(5)
    y = 100*np.random.rand(5)
    c = np.random.rand(5)
    
    fig, ax = plt.subplots()
    sc = plt.scatter(x, y, c=c, cmap='viridis')
    
    # I want to annotate the third point (idx=2)
    idx = 2  
    ax.annotate("hello", xy=(x[idx],y[idx]), color=sc.to_rgba(c[idx]), 
                xytext=(5,5), textcoords="offset points")
    plt.show()
    

    【讨论】:

      【解决方案2】:

      如另一个答案所述,散点图是PathCollection。它有一个get_facecolors() 方法,该方法返回用于渲染每个点的颜色。但是,只有在渲染散点图后才会返回正确的颜色。所以,我们可以先触发一个plt.draw(),然后再使用get_facecolors()

      工作示例:

      import matplotlib.pyplot as plt
      import numpy as np
      
      x = 100*np.random.rand(5)
      y = 100*np.random.rand(5)
      c = np.random.rand(5)
      
      fig, ax = plt.subplots()
      sc = ax.scatter(x, y, c=c, cmap='viridis')
      
      idx = 2  
      plt.draw()
      
      col = sc.get_facecolors()[idx].tolist()
      
      ax.annotate("hello", xy=(x[idx],y[idx]), color=col, 
                  xytext=(5,5), textcoords="offset points")
      plt.show()
      

      生成

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-07-20
        • 2016-05-04
        • 2011-08-29
        • 1970-01-01
        • 2017-10-12
        • 2014-09-10
        • 1970-01-01
        相关资源
        最近更新 更多