[英]Displaying lowest values as white
我有以下 3x3 矩阵,我想要 plot:
import matplotlib.cm
import matplotlib.pyplot as plt
import numpy as np
import copy
cmap = copy.copy(cm.get_cmap("Blues"))
cmap.set_bad('white')
fig = plt.figure(figsize=(15, 10))
img = np.array([[-0.9, -0.5599234, 0.21042876],[-0.42735877, 0.61514954, -0.74305015],[0.61958201, -0.04358633, 0.78672511]])
im = plt.imshow(img, origin='upper', cmap=cmap)
结果如下所示:
可见,左上角的条目最小,应显示为白色。 如何更改它以使最小的条目显示为白色?
其次,有没有办法调整颜色图,使其以较暗的值开始?
让颜色图以白色开始的一种方法是创建ListedColormap
,例如从white
变为darkblue
蓝色。 要从最暗的颜色开始,只需反转 ListedColormap 的ListedColormap
列表。
可以反转标准颜色图,只需在其名称末尾 附加_r
即可。
创建从中档到深蓝色的颜色图的一种方法是创建ListedColormap
,其中 rgb 值以十六进制形式给出。
这里有些例子:
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
import numpy as np
img = np.array([[-0.9, -0.5599234, 0.21042876], [-0.42735877, 0.61514954, -0.74305015], [0.61958201, -0.04358633, 0.78672511]])
fig, axs = plt.subplots(ncols=3, figsize=(12, 5))
cmap0 = LinearSegmentedColormap.from_list('', ['white', 'darkblue'])
cmap1 = 'Blues_r'
cmap2 = LinearSegmentedColormap.from_list('', ['#aaddee', '#000077'])
for ax, cmap in zip(axs, [cmap0, cmap1, cmap2]):
im = ax.imshow(img, origin='upper', cmap=cmap)
plt.colorbar(im, ax=ax, orientation='horizontal', pad=0.05)
ax.set_xticks([0, 1, 2])
ax.set_yticks([0, 1, 2])
ax.tick_params(labelbottom=False, labelleft=False, length=0) # hide ticks, but use position for a grid
ax.grid(True, color='white')
axs[0].set_title("Colormap from white to darkblue")
axs[1].set_title("Reversed blues colormap")
axs[2].set_title("Custom darker blues colormap")
plt.show()
同样令人感兴趣的可能是 Seaborn 的调色板函数,它提供了创建颜色图的其他方法(这些函数需要参数as_cmap=True
才能返回颜色图)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.