我在Matplotlib上已存在的图像上创建了一个简单的热图,现在我试图显示单元格上的值,但是问题是这些值不会进入热图内部,而是整个图像内, here是屏幕截图。
我认为这是因为我正在图像顶部生成热图,但是我不知道该如何解决。这是我的代码:
fig,ax = plt.subplots(1)
ax.imshow(im)
a = [[0.0233188 0.0232844 0.0233099 0.0242786 ]
[0.0233158 0.023217 0.02370096 0.02434176]
[0.02328474 0.02319508 0.02433976 0.02290478]
[0.02320107 0.02345002 0.02484117 0.02355316]
[0.02317872 0.02374418 0.02374605 0.02157998]]
ax1 = fig.add_subplot(111)
bounds1 = sorted([0.023, np.amin(a), np.amax(a)])
norm1 = matplotlib.colors.TwoSlopeNorm(vcenter=bounds1[1], vmin=bounds1[0], vmax=bounds1[2])
Map = ax1.imshow(a, interpolation='none', norm=norm1, extent=[0, 1.15, 0, 0.85])
x1 = [1, 2, 3, 4]
y1 = [1, 2, 3, 4, 5]
for i in range(len(y1)):
for j in range(len(x1)):
text = ax1.text(j, i, a[i, j],
ha="center", va="center", color="r")
答案 0 :(得分:2)
extent=[x0, x1, y0, y1]
更改图像的x和y坐标。当x0和x1之间有N个像元时,可以通过将距离分成2N+1
个部分并取1st ,3 rd ,5 来找到像元中心。那个列表的位置。
请注意,由于imshow(a, ...)
未使用origin='lower'
,因此这些值是相反的。因此,对于y位置,需要以相反的顺序遍历。
from matplotlib import pyplot as plt
import matplotlib
import numpy as np
fig, ax = plt.subplots()
ax.axis('off')
a = np.array([[0.0233188, 0.0232844, 0.0233099, 0.0242786],
[0.0233158, 0.023217, 0.02370096, 0.02434176],
[0.02328474, 0.02319508, 0.02433976, 0.02290478],
[0.02320107, 0.02345002, 0.02484117, 0.02355316],
[0.02317872, 0.02374418, 0.02374605, 0.02157998]])
ax1 = fig.add_subplot(111)
bounds1 = sorted([0.023, np.amin(a), np.amax(a)])
norm1 = matplotlib.colors.TwoSlopeNorm(vcenter=bounds1[1], vmin=bounds1[0], vmax=bounds1[2])
x0, x1, y0, y1 = 0, 1.15, 0, 0.85
Map = ax1.imshow(a, interpolation='none', norm=norm1, extent=[x0, x1, y0, y1])
for i, yi in enumerate(np.linspace(y0, y1, 2 * a.shape[0] + 1)[-2::-2]):
for j, xj in enumerate(np.linspace(x0, x1, 2 * a.shape[1] + 1)[1::2]):
text = ax1.text(xj, yi, f'{a[i, j]:.6f}',
ha="center", va="center", color='darkred' if a[i, j] > bounds1[1] else 'white', fontsize=10)
plt.show()