[英]Making a custom colormap using matplotlib in python
我有一個用matplotlib顯示的圖像。
該圖像由以下代碼生成:
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)
我想應用自定義色圖,以便值:
任何幫助將不勝感激。
這樣做的方法不止一種。 在您的情況下,最簡單的方法是使用LinearSegmentedColormap.from_list
並指定顏色的相對位置以及顏色名稱。 (如果你有均勻間隔的變化,你可以跳過元組,只做from_list('my cmap', ['blue', 'white', 'red'])
。)然后你需要指定一個手動min和最大數據( vmin
和vmax
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()
這聽起來像地震色圖
您可能希望強制使用最小值和最大值來使中間變為白色。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.