【问题标题】:How can I get the matplotlib rgb color, given the colormap name, BoundryNorm, and 'c='?给定颜色图名称、BoundryNorm 和“c=”,如何获得 matplotlib rgb 颜色?
【发布时间】:2014-11-24 08:23:51
【问题描述】:

我如何获得一个数字 NUM 的 matplotlib rgb 值:

  1. 颜色图('autumn_r' 在下面的示例中为黄色到红色)
  2. BoundryNorm 值(以下示例中的“2 到 10”)
  3. 数字 NUM

在我的例子中,我想:

  1. 给定任何小于或等于 2 的值,返回黄色的 rgb 值。
  2. 给定任何 10 或更大的值,返回红色的 rgb 值。
  3. 给定 3

下面的代码显示了颜色图的使用和定义我的边界值。现在我只需要一个函数来返回我的 rgb 值而不是做散点图。散点图仅用于可视化,因此我可以看到标准化正在按我的意愿工作。

import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib import cm
import numpy as np
import copy

# setup the plot
fig, ax = plt.subplots(1,1, figsize=(6,6))

# define the data
NUM_VALS = 20
NORM_ENDS = (2,10)
x = np.random.uniform(0, NUM_VALS, size=NUM_VALS)
y = np.random.uniform(0, NUM_VALS, size=NUM_VALS)
tag = copy.deepcopy(y)

# define the colormap
cmap = plt.get_cmap('autumn_r')
cmaplist = [cmap(i) for i in range(cmap.N)]

# create the new map
cmap = cmap.from_list('Custom cmap', cmaplist[0:], cmap.N)

# define the bins and normalize
bounds = np.linspace(NORM_ENDS[0], NORM_ENDS[1], NORM_ENDS[1]-NORM_ENDS[0]+1)
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

# make the scatter
scat = ax.scatter(x,y,s=300, c=tag,cmap=cmap,norm=norm)

# create a second axes for the colorbar
ax2 = fig.add_axes([0.90, 0.1, 0.03, 0.8])
cb = mpl.colorbar.ColorbarBase(ax2, cmap=cmap, norm=norm, spacing='proportional', ticks=bounds, boundaries=bounds, format='%1i')

ax.set_title('Well defined discrete colors')
ax2.set_ylabel('Very custom cbar [-]', size=12)

plt.show()

【问题讨论】:

    标签: python matplotlib rgb colormap


    【解决方案1】:

    知道了。我创建了一个包含“get_rgb”函数的颜色图辅助对象:

    import matplotlib as mpl
    import matplotlib.pyplot as plt
    from matplotlib import cm
    
    class MplColorHelper:
    
      def __init__(self, cmap_name, start_val, stop_val):
        self.cmap_name = cmap_name
        self.cmap = plt.get_cmap(cmap_name)
        self.norm = mpl.colors.Normalize(vmin=start_val, vmax=stop_val)
        self.scalarMap = cm.ScalarMappable(norm=self.norm, cmap=self.cmap)
    
      def get_rgb(self, val):
        return self.scalarMap.to_rgba(val)
    

    以及示例用法:

    import numpy as np
    # setup the plot
    fig, ax = plt.subplots(1,1, figsize=(6,6))
    
    # define the data between 0 and 20
    NUM_VALS = 20
    x = np.random.uniform(0, NUM_VALS, size=NUM_VALS)
    y = np.random.uniform(0, NUM_VALS, size=NUM_VALS)
    
    # define the color chart between 2 and 10 using the 'autumn_r' colormap, so
    #   y <= 2  is yellow
    #   y >= 10 is red
    #   2 < y < 10 is between from yellow to red, according to its value
    COL = MplColorHelper('autumn_r', 2, 10)
    
    scat = ax.scatter(x,y,s=300, c=COL.get_rgb(y))
    ax.set_title('Well defined discrete colors')
    plt.show()
    

    【讨论】:

      【解决方案2】:

      这就够了。

      In [22]:
      
      def cstm_autumn_r(x):
          return plt.cm.autumn_r((np.clip(x,2,10)-2)/8.)
      In [23]:
      
      cstm_autumn_r(1.4)
      Out[23]:
      (1.0, 1.0, 0.0, 1.0) #rgba yellow
      In [24]:
      
      cstm_autumn_r(10.5) #rgba red
      Out[24]:
      (1.0, 0.0, 0.0, 1.0)
      In [25]:
      
      %matplotlib inline
      x = np.linspace(0, 15)
      plt.scatter(x,x, c=cstm_autumn_r(x))
      

      【讨论】:

      • 很好 - 你能解释一下“8”的意义吗 - 是界限、10 和 2 之间的差异,还是其他什么?
      • @dreab,是的,这是界限之间的差异:本质上,原始数据被投影到 [2,10],大于 10 的值将获得相同的颜色,小于 2 的值将获得与 2 相同的颜色。
      • 谢谢 - 很好的解决方案。强烈推荐,因为我也根据中值在 seaborn boxplot 中工作。 ;)
      【解决方案3】:
      cmap = plt.get_cmap(cmap_name)
      rgb_cm = cmap.colors  # returns array-like color
      

      【讨论】:

      • 这适用于哪个 matplotlib 版本?它为版本 3+ 提供 AttributeError: 'LinearSegmentedColormap' object has no attribute 'colors'
      • colors won't work, use this - from matplotlib import cm cm.jet(0) ... cm.jet(255) 返回 rgb 的值,范围为 0-1,如果最后一个索引是 alpha你有它,通常它设置为 1。
      猜你喜欢
      • 1970-01-01
      • 2011-11-27
      • 1970-01-01
      • 1970-01-01
      • 2014-09-01
      • 1970-01-01
      • 2015-09-29
      • 1970-01-01
      • 2018-12-23
      相关资源
      最近更新 更多