问题描述
我正在尝试使用 matplotlib 在 python 中绘制一个小图像,并希望显示的轴与生成它的 numpy 数组具有相同的形状,即不应重新采样数据.换句话说,阵列中的每个条目应对应于屏幕上的一个像素(或其附近).这看似微不足道,但即使拖曳了一段时间的互联网,我似乎也无法正常工作:
I'm trying to plot a small image in python using matplotlib and would like the displayed axes to have the same shape as the numpy array it was generated from, i.e. the data should not be resampled. In other words, each entry in the array should correspond to a pixel (or thereabouts) on the screen. This seems trivial, but even after trawling the internet for while, I can't seem to get it to work:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
X = np.random.rand(30,40)
fig = plt.figure()
fig.add_axes(aspect="equal",extent=[0, X.shape[1], 0, X.shape[0]])
ax = fig.gca()
ax.autoscale_view(True, False, False)
ax.imshow(X, cmap = cm.gray)
plt.show()
推荐答案
我自己也遇到过同样的问题.如果 imshow
的 interpolation='nearest'
选项不够好,那么如果您的主要目标是查看原始、未缩放、未插值、未在 matplotlib 中搞砸了像素,然后你就无法击败 figimage
恕我直言.演示:
I've had the same problem myself. If the interpolation='nearest'
option to imshow
isn't good enough, well if your main objective is to see raw, un-scaled, non-interpolated, un-mucked about pixels in matplotlib, then you can't beat figimage
IMHO. Demo:
import numpy as np
import numpy.random
import matplotlib.pyplot as plt
a=256*np.random.rand(64,64)
f0=plt.figure()
plt.imshow(a,cmap=plt.gray())
plt.suptitle("imshow")
f1=plt.figure()
plt.figimage(a,cmap=plt.gray())
plt.suptitle("figimage")
plt.show()
当然这意味着放弃轴(或以某种方式自己绘制它们). figimage
有一些选项,可让您在图形周围移动图像,所以我想可能可以在通过其他方法创建的某些轴上进行操纵.
Of course it means giving up the axes (or drawing them yourself somehow). There are some options to figimage
which let you move the image around the figure so I suppose it might be possible to manoeuvre them on top of some axes created by other means.
这篇关于matplotlib 绘制小图像而无需重新采样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!