我有一个大小为 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()
最佳答案
我不清楚你为什么要添加[' | '] 和 ['|'] 在标签前面,所以我从代码中删除了它。色标对我有用(参见代码),我相信您的数据有问题。
下面的代码使用 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/