Python热图绘制颜色条

时间:2016-03-31 21:15:11

标签: python matplotlib heatmap

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

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

我可以看到颜色条以及它们上的单元格值。我需要在代码中添加什么来获取这些内容?

由于

2 个答案:

答案 0 :(得分:5)

你看过seaborn吗?

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

The Exceptional Performance of Lil' Exception

答案 1 :(得分:3)

对于颜色条,请参阅this example。你猜对了,正确的函数调用只是ax.colorbar()

关于pcolor图上的值,我担心您必须使用ax.text()“手动”添加它们。计算并循环单元格中心值并调用text()函数。您可以使用关键字参数horizontalalignment='center'verticalalignment='center'来保持文本值以x, y为中心。

相关问题