【发布时间】:2019-09-05 00:59:11
【问题描述】:
由于某种原因在matplotlib中设置轴范围绘制图像偏移,如何解决这个问题?
sz = 16
img = np.zeros((sz,sz), np.uint8)
img[:2,:] = 255
img[-2:,:] = 255
img[:,:2] = 255
img[:,-2:] = 255
img[sz//2-1:sz//2+1,sz//2-1:sz//2+1] = 255
print('img.shape', img.shape)
# v1
# axes = plt.gca()
# axes.set_xlim([0,sz])
# axes.set_ylim([0,sz])
# v2
plt.axis([0, sz, 0, sz])
plt.imshow(img, interpolation='nearest')
plt.show()
更新:
更新:
基于@ImportanceOfBeingErnest 的回答,刻度以像素中心为中心,但我需要它们以像素角为中心。
sz = 8
img = np.zeros((sz,sz), np.uint8)
img[:1,:] = 255
img[-1:,:] = 255
img[:,:1] = 255
img[:,-1:] = 255
img[sz//2-1:sz//2+1,sz//2-1:sz//2+1] = 255
print('img.shape', img.shape)
plt.axis([-0.5, img.shape[1]-0.5, img.shape[0]-0.5, -0.5])
plt.imshow(img)
plt.show()
更新:
根据@haijohn 的回答,水平刻度不在每个像素处。
sz = 8
img = np.zeros((sz,sz), np.uint8)
img[:1,:] = 255
img[-1:,:] = 255
img[:,:1] = 255
img[:,-1:] = 255
img[sz//2-1:sz//2+1,sz//2-1:sz//2+1] = 255
print('img.shape', img.shape)
plt.axis([0, img.shape[1], img.shape[0], 0])
plt.imshow(img, extent=[0, sz, 0, sz], interpolation='nearest')
plt.show()
【问题讨论】:
-
在
plt.axis([0, sz, 0, sz])中将sz设置为sz-1似乎可以解决问题 -
@Axois 使用 sz-1 它仍然绘制不正确的轴,请参阅更新。
标签: python matplotlib jupyter-notebook