简体   繁体   中英

matplotlib.pyplot.imshow: removing white space within plots when using attributes “sharex” and “sharey”

I have a problem which is similar to the one posted here . The difference is that I get unwanted white spaces inside the plot area when I plot two subplots which share axes via the sharex and sharey attributes. The white spaces persist even after setting autoscale(False) . For example, using similar code as in the answer to the post mentioned above:

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(2, 1, 1)
ax.imshow(np.random.random((10,10)))
ax.autoscale(False)
ax2 = fig.add_subplot(2, 1, 2, sharex=ax, sharey=ax)   # adding sharex and sharey
ax2.imshow(np.random.random((10,10)))
ax2.autoscale(False)
plt.show()

results in this image.

I have also tried ax.set_xlim(0, 10) and ax.set_xbound(0, 10) as per suggestions here , but to no avail. How can I get rid of the extra white spaces? Any ideas would be appreciated.

As suggested here , adding:

ax.set_adjustable('box-forced')
ax2.set_adjustable('box-forced')

solves the problem.

( documentation )

Using plt.subplots as:

fig, ax = plt.subplots(nrows=2, ncols=1, sharex=True, sharey=False)
ax[0].imshow(np.random.random((10,10)))
ax[0].autoscale(False)
ax[1].imshow(np.random.random((10,10)))
ax[1].autoscale(False)

I get 这个数字 with no white spaces within axes. Using figsize within plt.subplots or fig.subplots_adjust you can get better axis ratios.

The issue is the helpful machinery from using add_subplot . Notice that the amount of white space changes if you resize the figure.

The following seems to work (until you re-size the figure)

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(figsize=(5, 5))
ax = fig.add_axes([.3, .55, .35, .35]) 
ax.imshow(np.random.random((10,10)))
ax.autoscale(False)
ax2 = fig.add_axes([.3,  .05, .35, .35], sharex=ax, sharey=ax ) 
ax2.imshow(np.random.random((10,10)))
ax2.autoscale(False)

plt.show()

This looks like a bad interaction between the size/location of the axes object, the shared axes, and the equal aspect ratio from imshow .

If you can live with out the ticks, you can do

ax.set_axis_off()
ax2.set_axis_off()

I think it is worth opening an issue on the matplotlib github for this.

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