How to set tight_layout for matplotlib graphs after show()

冷暖自知 提交于 2019-12-03 15:32:37

You can achieve what you want with the help of Matplotlib event handling. Just write a small function that calls tight_layout and updates the figure every time the figure is resized:

from matplotlib import pyplot as plt
import numpy as np

x = np.linspace(0,np.pi,100)
y1 = np.sin(x)
y2 = np.cos(x)
fig, (ax1,ax2) = plt.subplots(nrows=1, ncols=2)
fig.tight_layout()
ax1.plot(x,y1)
ax2.plot(x,y2)

def on_resize(event):
    fig.tight_layout()
    fig.canvas.draw()

cid = fig.canvas.mpl_connect('resize_event', on_resize)

plt.show()

There is of course a small chance that this is system or version dependent. I verified the above example on MacOS Sierra with Python 3.5.4 (Matplotlib 2.0.2) and with Python 2.7.14 (Matplotlib 2.1.0). Hope this helps.

EDIT:

In fact, I think your keypress handler would have worked if you would have updated the figure after tight_layout, i.e. if you would have called fig.canvas.draw().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!