简体   繁体   English

在python中使用matplotlib制作自定义色彩映射表

[英]Making a custom colormap using matplotlib in python

I have an image that I'm showing with matplotlib. 我有一个用matplotlib显示的图像。

在此输入图像描述

The image is generated by the following code: 该图像由以下代码生成:

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


labels = ['Name1', 'Name2', 'Name3', 'Name4', 'Name5', 'Name6']

data = np.array(
 [[ 0.000, 0.120, 0.043, 0.094, 0.037, 0.045],
  [ 0.120, 0.000, 0.108, 0.107, 0.105, 0.108],
  [ 0.043, 0.108, 0.000, 0.083, 0.043, 0.042],
  [ 0.094, 0.107, 0.083, 0.000, 0.083, 0.089],
  [ 0.037, 0.105, 0.043, 0.083, 0.000, 2.440],
  [ 0.045, 0.108, 0.042, 0.089, 2.440, 0.000]])


mask =  np.tri(data.shape[0], k=-1)
data = np.ma.array(data, mask=mask) # Mask out the lower triangle of data.

fig, ax = plt.subplots(sharex=True)
im = ax.pcolor(data, edgecolors='black', linewidths=0.3)

# Format
fig = plt.gcf()
fig.set_size_inches(10, 10)

ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False)
ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False)

# Turn off the frame.
ax.set_frame_on(False)
ax.set_aspect('equal')  # Ensure heatmap cells are square.

# Want a more natural, table-like display.
ax.invert_yaxis()
ax.yaxis.tick_right()
ax.xaxis.tick_top()

ax.set_xticklabels(labels, minor=False)
ax.set_yticklabels(labels, minor=False)

# Rotate the upper labels.
plt.xticks(rotation=90)
ax.grid(False)
ax = plt.gca()

for t in ax.xaxis.get_major_ticks():
    t.tick1On = False
    t.tick2On = False
for t in ax.yaxis.get_major_ticks():
    t.tick1On = False
    t.tick2On = False

fig.colorbar(im)

fig.savefig('out.png', transparent=False, bbox_inches='tight', pad_inches=0)

I'd like to apply a custom colormap so that values: 我想应用自定义色图,以便值:

  • between 0-1 are linear gradient from blue and white 0-1之间是蓝色和白色的线性梯度
  • between 1-3 are linear gradient from white and red. 1-3之间是白色和红色的线性渐变。

Any help will be greatly appreciated. 任何帮助将不胜感激。

There's more than one way to do this. 这样做的方法不止一种。 In your case, it's easiest to use LinearSegmentedColormap.from_list and specify relative positions of colors as well as the colornames. 在您的情况下,最简单的方法是使用LinearSegmentedColormap.from_list并指定颜色的相对位置以及颜色名称。 (If you had evenly-spaced changes, you could skip the tuples and just do from_list('my cmap', ['blue', 'white', 'red']) .) You'll then need to specify a manual min and max to the data (the vmin and vmax kwargs to imshow / pcolor /etc). (如果你有均匀间隔的变化,你可以跳过元组,只做from_list('my cmap', ['blue', 'white', 'red']) 。)然后你需要指定一个手动min和最大数据( vminvmax kwargs到imshow / pcolor / etc)。

As an example: 举个例子:

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

data = np.array(
             [[ 0.000, 0.120, 0.043, 0.094, 0.037, 0.045],
              [ 0.120, 0.000, 0.108, 0.107, 0.105, 0.108],
              [ 0.043, 0.108, 0.000, 0.083, 0.043, 0.042],
              [ 0.094, 0.107, 0.083, 0.000, 0.083, 0.089],
              [ 0.037, 0.105, 0.043, 0.083, 0.000, 2.440],
              [ 0.045, 0.108, 0.042, 0.089, 2.440, 0.000]])
mask = np.tri(data.shape[0], k=-1)
data = np.ma.masked_where(mask, data)

vmax = 3.0
cmap = LinearSegmentedColormap.from_list('mycmap', [(0 / vmax, 'blue'),
                                                    (1 / vmax, 'white'),
                                                    (3 / vmax, 'red')]
                                        )

fig, ax = plt.subplots()
im = ax.pcolor(data, cmap=cmap, vmin=0, vmax=vmax, edgecolors='black')
cbar = fig.colorbar(im)

cbar.set_ticks(range(4)) # Integer colorbar tick locations
ax.set(frame_on=False, aspect=1, xticks=[], yticks=[])
ax.invert_yaxis()

plt.show()

在此输入图像描述

This sounds like the seismic colormap 这听起来像地震色图

You might want to force the minimum and maximum to get the middle to be white. 您可能希望强制使用最小值和最大值来使中间变为白色。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM