matplotlib 轴标签未与数据箱对齐

matplotlib axis labels not aligned with data bins

我正在尝试绘制一个相关矩阵,而不是 bin 编号作为标签(参见 y 轴标签)我想要物理的实际单位(x 轴标签)。不幸的是,我无法将 xticks 与垃圾箱的中心对齐,而且我不明白为什么矩阵的每一列都没有标签。

下面的代码生成图:

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
labels =['', '0.13','0.20','0.32','0.50','0.79','1.26','2.00','3.16','5.01']
plt.xticks(range(len(labels)+1), labels, size='small')
#The '+1 in range seems needed as if I don't include it the first label is not displayed at all
plt.imshow(np.corrcoef(bootstrap_samples_matrix.transpose()), interpolation='nearest', cmap=plt.cm.Reds, extent=(0.5,10.5,0.5,10.5), align="center")
plt.colorbar()

您将 xticks 设置为标签定义的位置,但实际上它们并不相同。我想你想将标签设置为实际位置,像这样;

替换:plt.xticks(范围(len(labels)+1), labels, size='small')

有:ax.set_xticklabels(标签,minor=False)

要将 xticks 与 bin 的中心对齐并在矩阵的每一列都有一个标签,可以通过手动设置标签来实现。

fig = plt.figure()
ax = fig.add_subplot(1,1,1)

manual_labels =['0.20','0.32','0.50','0.79','1.26','2.00','3.16']
ax.set_xticks([0.5,1.5,2.5,3.5,4.5,5.5,6.5,7.5])
ax.set_xticklabels(manual_labels, minor=False)

ax.set_yticks([0.5,1.5,2.5,3.5,4.5,5.5,6.5,7.5])
ax.set_yticklabels(manual_labels, minor=False)