matplotlib 如何在Python中创建一个从绿色到红色的热图?

ewm0tg9j  于 2023-05-23  发布在  Python
关注(0)|答案(3)|浏览(167)

我试图绘制范围为-3到3的对数比,并希望负比率为绿色,正比率为红色,对数比为0(中心)为白色。matplotlib中现有的配色方案都没有提供这个选项,我还没有弄清楚如何手动输出一个漂亮的渐变。

zpgglvta

zpgglvta1#

使用matplotlib.colors.LinearSegmentedColormapfrom_list方法似乎比这里的其他一些答案更直观。

from  matplotlib.colors import LinearSegmentedColormap
cmap=LinearSegmentedColormap.from_list('rg',["r", "w", "g"], N=256)

或用于更复杂的调谐:

from  matplotlib.colors import LinearSegmentedColormap
c = ["darkred","red","lightcoral","white", "palegreen","green","darkgreen"]
v = [0,.15,.4,.5,0.6,.9,1.]
l = list(zip(v,c))
cmap=LinearSegmentedColormap.from_list('rg',l, N=256)

8gsdolmq

8gsdolmq2#

您可以使用LinearSegmentedColormap创建自己的。我喜欢将红色和绿色通道的上限和下限设置为小于1.0,这样颜色就不会太亮(这里我使用了0.8)。根据你的口味调整。
更多细节请参见matplotlib网站上的custom_cmap example
下面是一个工作示例:

import matplotlib.pyplot as plt
import matplotlib.colors as colors
import numpy as np

# This dictionary defines the colormap
cdict = {'red':  ((0.0, 0.0, 0.0),   # no red at 0
                  (0.5, 1.0, 1.0),   # all channels set to 1.0 at 0.5 to create white
                  (1.0, 0.8, 0.8)),  # set to 0.8 so its not too bright at 1

        'green': ((0.0, 0.8, 0.8),   # set to 0.8 so its not too bright at 0
                  (0.5, 1.0, 1.0),   # all channels set to 1.0 at 0.5 to create white
                  (1.0, 0.0, 0.0)),  # no green at 1

        'blue':  ((0.0, 0.0, 0.0),   # no blue at 0
                  (0.5, 1.0, 1.0),   # all channels set to 1.0 at 0.5 to create white
                  (1.0, 0.0, 0.0))   # no blue at 1
       }

# Create the colormap using the dictionary
GnRd = colors.LinearSegmentedColormap('GnRd', cdict)

# Make a figure and axes
fig,ax = plt.subplots(1)

# Some fake data in the range -3 to 3
dummydata = np.random.rand(5,5)*6.-3.

# Plot the fake data
p=ax.pcolormesh(dummydata,cmap=GnRd,vmin=-3,vmax=3)

# Make a colorbar
fig.colorbar(p,ax=ax)

plt.show()

fcg9iug3

fcg9iug33#

下面是使用LinearSegmentedColormap的例子:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LinearSegmentedColormap

cmapGR = LinearSegmentedColormap(
    'GreenRed',
    {
        'red':  ((0.0, 0.0, 0.0),
                (0.5, 1.0, 1.0),
                (1.0, 1.0, 1.0)),
        'green':((0.0, 1.0, 1.0),
                (0.5, 1.0, 1.0),
                ( 1.0, 0.0, 0.0)),
        'blue': ((0.0, 0.0, 0.0),
                (0.5, 1.0, 1.0),
                (1.0, 0.0, 0.0))
    },)

plt.imshow(np.array([np.arange(200) for i in range(200)]), cmap=cmapGR)
plt.show()

它生成以下

参见例如http://matplotlib.org/examples/pylab_examples/custom_cmap.html以了解更多用法和其他示例。

相关问题