我正在尝试使用 matplotlib 库和 python 3 将颜色映射应用于二维数组。为了简单起见,我制作了一个示例代码来显示我的问题:
示例代码:
from matplotlib import pyplot as plt
from matplotlib import colors
import numpy as np
#just an example array
sample= np.zeros((20,20),dtype=int)
sample[2,2]=sample[4,4]=2
#color-table and color bounds
cmap = colors.ListedColormap(['black','white','red','green'])
bounds=[-6,0,1,99,105]
norm = colors.BoundaryNorm(bounds, cmap.N)
fig, ax = plt.subplots()
ax.imshow(sample,interpolation='nearest', cmap=cmap, norm=norm)
ax.grid(which='major', axis='both', linestyle='-', color='k', linewidth=2)
ax.set_xlim(0, 20)
ax.set_ylim(20, 0)
ax.set_xticks(np.arange(0,20,1))
ax.set_yticks(np.arange(0,20,1))
plt.show()
使用此代码,我有一个 20 x 20 的网格,除了 [2,2]
和 [4,4]
两个单元格之外,网格到处都是白色的是红色的。问题是,当我显示网格时,单元格在两个方向上都偏离了 -0.5。我通过这个示例代码得到的是:
如果我将网格移动 -0.5:
ax.set_xticks(np.arange(-0.5,20,1))
ax.set_yticks(np.arange(-0.5,20,1))
我的代码有什么问题吗?我真的不明白这是怎么发生的?
最佳答案
ax.imshow
文档字符串的注释部分说:
Unless extent is used, pixel centers will be located at integer coordinates. In other words: the origin will coincide with the center of pixel (0, 0).
所以你的电话变成:
ax.imshow(sample, interpolation='none', cmap=cmap, norm=norm,
extent=[0, 20, 20, 0])
关于python-3.x - 我的 matplot 的网格偏离了 -0.5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50043810/