python - 在 python 中使用 matplotlib 制作自定义颜色图

标签 python matplotlib heatmap colorbar colormap

我有一张用 matplotlib 显示的图像。

enter image description here

图像由以下代码生成:

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)

我想应用自定义颜色图,以便值:

  • 0-1之间是从蓝到白的线性渐变
  • 1-3 是 白色和红色的线性渐变。

任何帮助将不胜感激。

最佳答案

有不止一种方法可以做到这一点。在您的情况下,最简单的方法是使用 LinearSegmentedColormap.from_list 并指定颜色的相对位置以及颜色名称。 (如果你有均匀间隔的变化,你可以跳过元组,只做 from_list('my cmap', ['blue', 'white', 'red'])。)你会然后需要为数据指定手动最小值和最大值(vminvmax kwargs 到 imshow/pcolor/ETC)。

举个例子:

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()

enter image description here

关于python - 在 python 中使用 matplotlib 制作自定义颜色图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24997926/

相关文章:

python - 在 ipython 中模拟 dreampie

python - 如何按 Pandas 中的中值对箱线图进行排序

python - 如何使用 matplotlib(无 Pandas )并排绘制两个图

python - matplotlib继承自datetime类plot

javascript - highcharts 热图 : arbitrarily set cell colors

R - 将多个热图堆叠在一起

r - 共现矩阵 - 热图

python - 如何使用产量打印字符串列表

python - 直接标签和悬停信息在 plotly 中有所不同

python - 在不指定 maxsize 参数的情况下使用 functools 的 @lru_cache