绘制热力图并添加颜色条

3
我正在处理一个目前看起来是这样的情节:

enter image description here

我正在使用以下代码:
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()

我想要的是这样的东西:

enter image description here

我在哪里可以看到彩色条以及它们上的数值。我需要在我的代码中添加什么来实现这个功能?

谢谢


在单元格文本方面有一些相关的内容:https://dev59.com/UGEi5IYBdhLWcg3wDoaV#21712361 - wflynny
1
对于色条,你尝试过 fig.colorbar(heatmap) 吗? - wflynny
2个回答

6
你有没有研究过seaborn?
import seaborn as sns
data = np.random.rand(2,2)
sns.heatmap(data, annot=True,  linewidths=.5)

enter image description here


哈哈,是的,这是一个很酷的库:https://stanford.edu/~mwaskom/software/seaborn/examples/您可以将 matplotlib 轴作为参数传递,并仍然使用所有 matplotlib 函数,例如 ax.set_xticks() sns.heatmap(data, annot=True, linewidths=.5, ax = ax) - Sam
如何在非IPython环境中运行它? - MartianMartian
哦,明白了。导入matplotlib.pyplot库并命名为plt。plt.show()。 - MartianMartian

5
对于色标,请参见这个示例。你猜对了,正确的函数调用只是ax.colorbar()
关于

pcolor

图上的数值,恐怕您需要使用ax.text()手动添加它们。计算并循环格子中心点的值,然后调用text()函数。您可以使用关键字参数horizontalalignment ='center'verticalalignment ='center'将文本值保持在x, y周围居中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接