更新matplotlib热图的美学

时间:2017-01-04 01:31:39

标签: python matplotlib seaborn

import matplotlib.pyplot as plt
import numpy as np
column_labels = list('ABCD')
row_labels = list('WXYZ')
data = np.random.rand(4,4)
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.set_label_position('top') # <-- This doesn't work!

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

以上代码来自:Moving x-axis to the top of a plot in matplotlib

如何更改此脚本的输出,使其在美学上看起来更像这张图片:
enter image description here

使用python matplotlib或seaborn的任何解决方案都有效。我想在细胞之间插入白色,细胞是正方形并且还控制它们的大小

1 个答案:

答案 0 :(得分:3)

我认为你需要两个技巧。首先,添加行

ax.set_aspect('equal')

使单元格显示为正方形(假设您在x轴和y轴上具有相同的数字,如示例中所示)。如果x轴上有x个正方形,y轴上有y个正方形,我怀疑你可以这样做,

ax.set_aspect(float(y) / float(x))

其次,您需要将edgecolor添加到单元格并使边缘变粗,因此将您的线条修改为例如,

heatmap = ax.pcolor(data, cmap=plt.cm.Blues, edgecolor='white', linewidths=10)

结果是

enter image description here