matplotlib:颜色条和文本标签

我想为热图创build一个颜色条图例,使标签位于每个离散颜色的中心。 请看下面的例子( 从这里借用 )

import matplotlib.pyplot as plt import numpy as np from matplotlib.colors import ListedColormap #discrete color scheme cMap = ListedColormap(['white', 'green', 'blue','red']) #data np.random.seed(42) data = np.random.rand(4, 4) fig, ax = plt.subplots() heatmap = ax.pcolor(data, cmap=cMap) #legend cbar = plt.colorbar(heatmap) cbar.ax.set_yticklabels(['0','1','2','>3']) cbar.set_label('# of contacts', rotation=270) # put the major ticks at the middle of each cell ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False) ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False) ax.invert_yaxis() #lebels column_labels = list('ABCD') row_labels = list('WXYZ') ax.set_xticklabels(column_labels, minor=False) ax.set_yticklabels(row_labels, minor=False) plt.show() 

它产生如下图: pmesh情节

理想情况下,我想要生成一个具有四种颜色和每种颜色的图例条,其中间有一个标签:0,1,2,3,> 4

 import matplotlib.pyplot as plt import numpy as np from matplotlib.colors import ListedColormap #discrete color scheme cMap = ListedColormap(['white', 'green', 'blue','red']) #data np.random.seed(42) data = np.random.rand(4, 4) fig, ax = plt.subplots() heatmap = ax.pcolor(data, cmap=cMap) #legend cbar = plt.colorbar(heatmap) cbar.ax.get_yaxis().set_ticks([]) for j, lab in enumerate(['$0$','$1$','$2$','$>3$']): cbar.ax.text(.5, (2 * j + 1) / 8.0, lab, ha='center', va='center') cbar.ax.get_yaxis().labelpad = 15 cbar.ax.set_ylabel('# of contacts', rotation=270) # put the major ticks at the middle of each cell ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False) ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False) ax.invert_yaxis() #lebels column_labels = list('ABCD') row_labels = list('WXYZ') ax.set_xticklabels(column_labels, minor=False) ax.set_yticklabels(row_labels, minor=False) plt.show() 

你非常接近。 一旦你有了一个颜色棒轴的参考,你可以做任何你想要的,包括把文字标签放在中间。 您可能想要使用格式来使其更明显。

演示