【问题标题】:How can I change the intensity of a colormap in matplotlib?如何更改 matplotlib 中颜色图的强度?
【发布时间】:2016-09-27 19:21:42
【问题描述】:

我使用matplotlib.pyplot.pcolor() 用 matplotlib 绘制热图:

import numpy as np
import matplotlib.pyplot as plt    

np.random.seed(1)
data =  np.sort(np.random.rand(8,12))
plt.figure()
c = plt.pcolor(data, edgecolors='k', linewidths=4, cmap='RdBu', vmin=0.0, vmax=1.0)
plt.colorbar(c)
plt.show()

如何更改'RdBu' 颜色图的强度?例如,如果颜色为(0, 0, 1),则应将其转换为(0, 0, 0.8)。更普遍, 如果颜色为(x, y, z),则应将其转换为(ax, ay, az),其中a 是介于0 和1 之间的某个标量。

【问题讨论】:

    标签: python matplotlib colormap


    【解决方案1】:

    您必须根据标准组装新的自定义颜色图。

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib import cm
    
    np.random.seed(1)
    data =  np.sort(np.random.rand(8,12))
    plt.figure()
    cmap = cm.get_cmap('RdBu', len(data)) # set how many colors you want in color map
    # modify colormap
    alpha = .5
    colors = []
    for ind in xrange(cmap.N):
        c = []
        for x in cmap(ind)[:3]: c.append(x*alpha)
        colors.append(tuple(c))
    my_cmap = matplotlib.colors.ListedColormap(colors, name = 'my_name')
    # plot with my new cmap
    cb = plt.pcolor(data, edgecolors='k', linewidths=4, cmap=my_cmap, vmin=0.0, vmax=1.0)
    plt.colorbar(cb)
    plt.show()
    

    【讨论】:

      【解决方案2】:

      这与 Stanley R(编辑:现在 Serenity)的答案非常相似,没有(在我看来)不必要的循环复杂性、附加到列表等:

      import numpy as np
      import matplotlib.pyplot as plt    
      from matplotlib.colors import ListedColormap
      
      a = 0.5
      
      # Get the colormap colors, multiply them with the factor "a", and create new colormap
      my_cmap = plt.cm.RdBu(np.arange(plt.cm.RdBu.N))
      my_cmap[:,0:3] *= a 
      my_cmap = ListedColormap(my_cmap)
      
      np.random.seed(1)
      data =  np.sort(np.random.rand(8,12))
      plt.figure()
      plt.subplot(121)
      c = plt.pcolor(data, edgecolors='k', linewidths=4, cmap='RdBu', vmin=0.0, vmax=1.0)
      plt.colorbar(c)
      plt.subplot(122)
      c = plt.pcolor(data, edgecolors='k', linewidths=4, cmap=my_cmap, vmin=0.0, vmax=1.0)
      plt.colorbar(c)
      plt.show()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-06-29
        • 2011-06-13
        • 1970-01-01
        • 2013-12-01
        • 2017-03-17
        • 2013-07-21
        相关资源
        最近更新 更多