Python 热图绘图颜色条

Python heatmap plot colorbar

到目前为止,我正在制作一个看起来像这样的情节:

我正在使用以下代码:

import matplotlib.pyplot as plt
import numpy as np
column_labels = ['A','B']
row_labels = ['A','B']
data = np.random.rand(2,2)
print(type(data))
data = np.array([[1, 0.232], [0.119, 1]])
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=plt.cm.Blues)

# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[0])+0.5, minor=False)
ax.set_yticks(np.arange(data.shape[1])+0.5, minor=False)

# want a more natural, table-like display
ax.invert_yaxis()
ax.xaxis.tick_top()

ax.set_xticklabels(row_labels, minor=False)
ax.set_yticklabels(column_labels, minor=False)
plt.show()

我想要得到的是这样的东西:

我可以在其中看到颜色条及其上单元格的值。我需要在我的代码中添加什么才能获得这些?

谢谢

有关颜色条,请参阅 this example. You guessed correctly, the right function call is just ax.colorbar()

关于 pcolor 图上的值,恐怕您必须使用 ax.text() 添加它们 "manually"。计算并遍历单元格中心值并调用 text() 函数。您可以使用关键字参数 horizontalalignment='center'verticalalignment='center' 使文本值以 x, y.

为中心

你看过seaborn吗?

import seaborn as sns
data = np.random.rand(2,2)
sns.heatmap(data, annot=True,  linewidths=.5)