简体   繁体   中英

Margins of matplotlib.pyplot.imshow when used in subplot environment

I am trying to plot the values of several arrays in separate plots of a figure using imshow.

When I plot one image only, and use the plt.imshow() command with the correct extents, the figure comes out perfectly. However, when I try to create multiple plots of this image in the same figure, using plt.subplot(), each of these plots ends up with incorrect x-axis settings, and there are white margins. I tried correcting the x-axis range with the set_xlim() command, but it has no effect (which I also don't understand).

The minimal working sample is below - any help would be appreciated!

from matplotlib import pyplot as plt
import numpy as n

image = n.array([[ 1.,  2.,  2.,  5.],
   [ 1.,  0.,  0.,  3.],
   [ 1.,  2.,  0.,  2.],
   [ 4.,  2.,  3.,  2.]])
xextent, yextent= n.shape(image)

fig, ax = plt.subplots(2,sharex=True, sharey=True)
im0 = ax[0].imshow(image, extent=(0,xextent,yextent,0),interpolation='nearest');
ax[0].set_xlim([0,4])
im1 = ax[1].imshow(image, extent=(0,xextent,yextent,0),interpolation='nearest');
ax[1].set_xlim([0,4])

plt.show()

在此处输入图片说明

I believe the reason for the whitespace is the size of the window. You can either change the window size (you'd have to figure out the numbers) or you can adjust the subplot. I found this out by playing with the "configure subplots" button in the image popup.

plt.subplots_adjust(right=0.4)

With this line the plot will have no whitespace, but still some empty space (which you can fix by adjusting the window size).

So the options are:

  1. Remove the sharex / sharey keywords - seems to clash with imshow in the subplot environment. (Suggested by xnx )

  2. Use plt.subplots_adjust with appropriate settings, in combination with plt.gcf().tight_layout() (Suggested by mwormser )

  3. Use pcolormesh instead of imshow in the subplot environment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM