Reputation: 1033
So I'm trying to get an intensity plot and an image of a spectrum snapped together in Matplotlib. But it just won't work. I tried most thing suggested in this and this question, but those are for the same kind of subplots, and none made the gap disappear. The one I used in my code, setting the keyword argument gridspec_kw = {'wspace':0, 'hspace':0}
in plt.subplots()
seemed to be the most reasonable to me, but it fails too. How should I eliminate all whitespace between the image and the plot?
My Matplotlib version is 2.2.2
.
Code:
impath = "Picture349.jpg" #a pic from the spectroscope
image = Image.open("Picture349.jpg")
imx, imy = image.size
imarray = np.asarray(image)
plt.imshow(image)
fig, (axint, axim) = plt.subplots(2,1, gridspec_kw = {'wspace':0, 'hspace':0}, sharex=True)
#get a single row of pixels from the middle of the image, extend and plot it
pixrownum = imy//2
colorcol = imarray[pixrownum]
rainbow = np.broadcast_to(colorcol, (100, *colorcol.shape))
axim.imshow(rainbow)
axim.get_yaxis().set_visible(False)
#get and plot intensity
bw = image.convert("L")
xcoords = np.arange(imx)
bwarray = np.asarray(bw)
axint.plot(xcoords, bwarray[pixrownum], "b")
axint.get_xaxis().set_visible(False)
plt.show()
Upvotes: 1
Views: 201
Reputation: 25363
The problem arises because the aspect ratio of your image is set to "equal" by default in plt.imshow()
. This is changing the layout of your subplots and interfering with the hspace
parameter.
There are 2 options that you have. First you can set the aspect ratio of your image to "auto" and keep hspace
at 0. However, if the aspect ratio is important, then you can manually adjust the hspace parameter by setting a negative value.
Using a simple example:
image = np.random.randint(0,20,(300,1300)) # fake data
# ====== Option 1 ======
fig, (axint, axim) = plt.subplots(2, 1, gridspec_kw = {'hspace':0})
axim.imshow(image, aspect="auto")
# ====== Option 2 ======
# fig, (axint, axim) = plt.subplots(2, 1, gridspec_kw = {'hspace':-0.23})
# axim.imshow(image)
axim.get_yaxis().set_visible(False)
axint.plot(np.arange(0,1300), np.random.randn(1300), "b")
axint.get_xaxis().set_visible(False)
plt.show()
Both methods give:
I think that option 1 is better if the aspect ratio is not important. Option 2 requires trial and error to find the right parameter for hspace
. In addition, if you change the figure size by dragging the window, option 2 will not scale properly
Upvotes: 1