python - 根据颜色图在条形图中的 y 值

标签 python matplotlib plot colorbar colormap

我已经在论坛上搜索过了,找到this ,但我的问题有点不同。 正如您从下面的代码和图片中看到的那样,我创建了一个带有颜色图“virdis”的 map 。 如何使用相同的颜色图创建单独的条形图?我想为 4 个颜色条(现在用简单颜色着色)着色,以便 y 轴上的值对应于颜色条的值,这可能吗?

我有这个矩阵:

矩阵=[[ 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, ax = plt.subplots(figsize=(7, 10))

im = ax.imshow(matrix, cmap='viridian')

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


divider = make_axes_locatable(ax)
axHistx1 = divider.append_axes("top", 1.2, pad=0.2, sharex=ax)
axHistx1.xaxis.set_tick_params(labelbottom=False)
axHistx2 = divider.append_axes("top", 1.2, pad=0.2, sharex=ax)
axHistx2.xaxis.set_tick_params(labelbottom=False)
axHistx3 = divider.append_axes("top", 1.2, pad=0.2, sharex=ax)
axHistx3.xaxis.set_tick_params(labelbottom=False)
axHistx4 = divider.append_axes("top", 1.2, pad=0.2, sharex=ax)
axHistx4.xaxis.set_tick_params(labelbottom=False)


cbaxes = fig.add_axes([0.125, 0.03, 0.774, 0.04])
cbar=fig.colorbar(im, label='match num.', cax = cbaxes, orientation="horizontal", boundaries=np.linspace(0,50,1001),
                  ticks=[0,10,20,30,40,50])
cbar.set_clim(0,50)


#print(matrix)
row0 = np.array(matrix[0,:])
row1 = np.array(matrix[1,:])
row2 = np.array(matrix[2,:])
row3 = np.array(matrix[3,:])
col0 = np.array(matrix[:,0]).T
col1 = np.array(matrix[:,1]).T
col2 = np.array(matrix[:,2]).T
col3 = np.array(matrix[:,3]).T
col4 = np.array(matrix[:,4]).T
col5 = np.array(matrix[:,5]).T
col6 = np.array(matrix[:,6]).T
col7 = np.array(matrix[:,7]).T
col8 = np.array(matrix[:,8]).T
col9 = np.array(matrix[:,9]).T

zbin = [0,1,2,3,4,5,6,7,8,9]
row0 = row0.ravel();row1 = row1.ravel();row2 = row2.ravel();row3 = row3.ravel();

axHistx1.bar(zbin, row3, color='orange', alpha=0.5, edgecolor=['orange']*len(zbin))
axHistx1.set_ylim(0,50)
axHistx1.set_ylabel('match')
axHistx2.bar(zbin, row2, color='r', alpha=0.5, edgecolor=['r']*len(zbin))
axHistx2.set_ylim(0,50)
axHistx2.set_ylabel('match')
axHistx3.bar(zbin, row1, color='g', alpha=0.5, edgecolor=['g']*len(zbin))
axHistx3.set_ylim(0,50)
axHistx3.set_ylabel('match')
axHistx4.bar(zbin, row0, color='cornflowerblue', alpha=0.8, edgecolor=['cornflowerblue']*len(zbin))
axHistx4.set_ylim(0,50)
axHistx4.set_ylabel('match')
ax.axis('tight')

plt.show()

enter image description here

最佳答案

要为条形图着色,您可以遍历条形图并设置颜色。这显示在例如在这个问题中Plot histogram with colors taken from colormap对于直方图。对于酒吧,它更容易,如图所示。在 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()

enter image description here

关于python - 根据颜色图在条形图中的 y 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49539105/

相关文章:

python - 获取其他两个字符串之间的中点字符串

python - numpy 数组的 glDrawPixels 未显示

python - Pandas :比较组内的行

python - 如何使用 Matplotlib GUI 而不是命令行提示来提示用户输入

python - 将容器添加到 python 中预先存在的对象的简单但正确的方法是什么?

python - 如何用分数标记 x 轴?

apache-spark - 如何在 Apache Spark (PySpark 1.4.1) 中可视化/绘制决策树?

python - 如何复制模块

R散点图: symbol color represents number of overlapping points

python - Pandas 按类别绘制数据框条形图和颜色