底部图表与顶部图表的标签重叠

Bottom graph is overlapping top graph's label

有什么问题吗?顶部图表的标签在底部图表下面......我真的无法想象如何解决这个问题。我认为它会正常工作。

下面的代码来自站点http://www.physics.nyu.edu/pine/pymanual/html/chap5/chap5_plot.html#basic-plotting

图表的形象在 link http://www.physics.nyu.edu/pine/pymanual/html/_images/subplotDemo.png 中。

我复制上面网站代码得到的图表图片在linkMy overlapped graph.

import numpy as np
import matplotlib.pyplot as plt

theta = np.arange(0.01, 8., 0.04)
y = np.sqrt((8./theta)**2-1.)
ytan = np.tan(theta)
ytan = np.ma.masked_where(np.abs(ytan)>20., ytan)
ycot = 1./np.tan(theta)
ycot = np.ma.masked_where(np.abs(ycot)>20., ycot)

plt.figure(1)

plt.subplot(2, 1, 1)
plt.plot(theta, y)
plt.plot(theta, ytan)
plt.ylim(-8, 8)
plt.axhline(color="gray", zorder=-1)
plt.axvline(x=np.pi/2., color="gray", linestyle='--', zorder=-1)
plt.axvline(x=3.*np.pi/2., color="gray", linestyle='--', zorder=-1)
plt.axvline(x=5.*np.pi/2., color="gray", linestyle='--', zorder=-1)
plt.xlabel("theta")
plt.ylabel("tan(theta)")

plt.subplot(2, 1, 2)
plt.plot(theta, -y)
plt.plot(theta, ycot)
plt.ylim(-8, 8)
plt.axhline(color="gray", zorder=-1)
plt.axvline(x=np.pi, color="gray", linestyle='--', zorder=-1)
plt.axvline(x=2.*np.pi, color="gray", linestyle='--', zorder=-1)
plt.xlabel("theta")
plt.ylabel("cot(theta)")

plt.show()

有一个非常简单的解决方案:在显示图表之前插入行 plt.tight_layout()。此行将自动调整子图之间的边距,因此一切看起来都很棒。

在您的代码中,它看起来像这样:

plt.tight_layout()
plt.show()

有关 tight_layout 的更多信息可在此处找到:Tight Layout Guide