要为条形着色,您可以循环遍历条形并设置颜色。例如,这显示为在这个问题中使用从颜色图中获取的颜色绘制直方图 https://stackoverflow.com/questions/23061657/plot-histogram-with-colors-taken-from-colormap对于直方图。对于酒吧来说更容易,如图所示在如何在 matplotlib 中将数字转换为色标? https://stackoverflow.com/questions/43009724/how-can-i-convert-numbers-to-a-color-scale-in-matplotlib
bars = plt.bar(x, y, color=list_of_colors)
现在您需要找出您真正想要为条形指定的颜色。为此,您将依赖于先前生成的图像的颜色图和规范,
plt.bar(x, y, color=im.cmap(im.norm(y)))
使用循环来消除冗余代码也很有意义subplots
代替make_axes_divisable
.
import numpy as np
import matplotlib.pyplot as plt
matrix=[[ 0, 0, 0, 0, 17, 25, 29, 35, 36, 41],
[16, 22, 17, 10, 9, 21, 23, 27, 26, 22],
[ 8, 19, 13, 16, 13, 5, 4, 11, 5, 4],
[ 3, 11, 10, 8, 7, 1, 0, 0, 0, 0]]
fig, axes = plt.subplots(nrows = 5, sharex=True, figsize=(6, 8),
gridspec_kw=dict(height_ratios=[1,1,1,1,3]))
fig.subplots_adjust(top=0.95, bottom=0.05)
ax = axes[-1]
im = ax.imshow(matrix, cmap='viridis', aspect="auto")
ax.set_xticks([0,1,2,3,4,5,6,7,8,9])
ax.set_xticklabels(['0.5','1.0','1.5','2.0','2.5','3.0','3.5','4.0','4.5','5.0'])
ax.set_xlabel('Redshift')
ax.set_yticks([-0.5,0.5,1.5,2.5,3.5])
ax.set_yticklabels(['50k','10k','1k','0.1k','0'])
ax.set_ylabel('counts')
#cbaxes = fig.add_axes([0.125, 0.03, 0.774, 0.04])
cbar=fig.colorbar(im, label='match num.', ax = axes[-1], pad=0.2,
orientation="horizontal", boundaries=np.linspace(0,50,1001),
ticks=[0,10,20,30,40,50])
cbar.set_clim(0,50)
zbin = [0,1,2,3,4,5,6,7,8,9]
for i, ax in enumerate(axes[:-1]):
y = np.array(matrix)[i,:]
bars = ax.bar(zbin, y, color=im.cmap(im.norm(y)))
ax.set_ylim(0,50)
ax.set_ylabel('match')
plt.show()