简体   繁体   中英

Why does matplotlib.gridspec's tight_layout not work correctly with pyplot.subplot whereas it does with fig.add_subplot?

I am trying to create two subplots next to one another using gridspec (the real plot is more complicated but this is the basic idea). I am creating the subplots using plt.subplot , but this does not seem to produce the expected result. I get only the second subplot on the right side of the figure, and not the first one.

On the other hand, if I create the subplots by using fig.add_subplot , the plot appears correctly although I get a tight_layout warning. I am a little surprised at this behaviour, since pyplot's subplot function internally calls fig.add_subplot (and then does some checking to see if the subplot already exists -- I guess?). Here is the code that produces only the rightmost subplot. Switching the comments to use plt.gcf().add_subplot gets it to work as expected.

from matplotlib import gridspec,pyplot as plt

gs = gridspec.GridSpec(1,1)
ax1 = plt.subplot(gs[0,0])
# ax1 = plt.gcf().add_subplot(gs[0,0])
ax1.plot(range(3),range(3))
gs.tight_layout(plt.gcf(),rect=[0,0,0.45,1])

gs = gridspec.GridSpec(1,1)
ax1 = plt.subplot(gs[0,0])
# ax1 = plt.gcf().add_subplot(gs[0,0])
ax1.plot(range(3),range(3))
gs.tight_layout(plt.gcf(),rect=[0.55,0,1,1])

plt.show()

Am I doing something wrong, or am I missing something here? For reference, here is what pyplot.subplot primarily does:

fig = gcf()
a = fig.add_subplot(*args, **kwargs)
bbox = a.bbox
byebye = []
for other in fig.axes:
    if other==a: continue
    if bbox.fully_overlaps(other.bbox):
        byebye.append(other)
for ax in byebye: delaxes(ax)

return a

My question is: why does using pyplot.subplot not produce the same result as fig.add_subplot?

What subplot does is checking for overlapping plots and deleting them if they exists. Your second subplot overlaps the first one so your second plt.subplot will delete the first one. Figure.add_subplot does not delete overlapping subplots.

Note that you are creating subplots that fill the whole figure:

gs = gridspec.GridSpec(1,1)
ax1 = plt.subplot(gs[0,0])

This is a subplot in a 1x1 grid so it will fill the whole figure and overlap any previous subplot.

BTW the issue has nothing to do with tight_layout which is working correctly..

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