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()
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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With