python - 使用 matplotlib 创建热图

标签 python numpy matplotlib

我有一个大小为 138 x 138 的 numpy 矩阵 fooarray。行和列中的每个条目都是一个单词。以下代码用于生成同一矩阵的热图。但我无法显示情节中的所有单词。

看起来显示的值在色阶上也是错误的。矩阵中的值范围为 3.2 到 -0.2,而热图中显示的值范围为 0.1 到 -0.1。如何使用 numpy 矩阵绘制热图?

fig = plt.figure()
ax = fig.add_subplot(111)

cax = ax.matshow(fooarray, interpolation='nearest', cmap='hot')
fig.colorbar(cax)

ax.set_xticklabels([' | '] + labels)
ax.set_yticklabels(['|'] + labels)

plt.show() 

enter image description here

最佳答案

我不清楚你为什么要添加[' | '] 和 ['|'] 在标签前面,所以我从代码中删除了它。色标对我有用(参见代码),我相信您的数据有问题。

下面的代码使用 set_xticks 控制刻度位置,并使用 ax.set_xticklabels 控制标签。我添加了 90 度旋转,但仍然很难获得具有 138 个刻度的可读标签。

import numpy as np
import matplotlib.pyplot as plt

#create test data:
s=138 #size of array
labels=[str(a) for a in range(s)]
fooarray=np.random.random(s*s).reshape((s,s))

#--- original code here:
fig = plt.figure()
ax = fig.add_subplot(111)

cax = ax.matshow(fooarray, interpolation='nearest', cmap='hot')
fig.colorbar(cax)
#----

#ticks and labels:
ax.set_xticks(range(len(labels)) , minor=False)
ax.set_xticklabels(labels)
ax.set_yticks(range(len(labels)) , minor=False)
ax.set_yticklabels(labels)
plt.xticks(rotation=90)

plt.show() 

关于python - 使用 matplotlib 创建热图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37662897/

相关文章:

Python/Scipy kde 拟合、缩放

python - Matplotlib PDF 后端慢?

python - 使用 python shell 的 SSH 和 exec channel

python - 扭曲的时间计数器

python - 使用 numpy 的矩阵的条件数

python - 多图中刻度线的长度相同

python - 完全删除图例 handle 和标签

python - 如何在 SQLAlchemy 中使用空集合进行分页查询?

python - 在 cx_Freeze 中打开自定义文件类型在打开文件时编译 python 可执行文件

python - 编写一个在 matlab 中可读的 3d numpy 数组