【发布时间】:2020-11-25 11:10:09
【问题描述】:
我正在尝试制作一个包含两个共享 x 轴的子图并且它们之间没有空间的图。我遵循了 matplotlib 库中的 Create adjacent subplots 示例。然而,我的情节需要有一个固定的大小,这使得一切变得复杂。如果我只是按照示例添加固定大小的图形大小,则标签被切断。如果我使用tight_layout 包含标签,那么这些图是间隔的。如何解决这个问题?此外,标题应该更接近图例。
非常感谢任何帮助!
示例程序,注释掉tight_layout看看有什么区别。
import numpy as np
import matplotlib.pyplot as plt
x_min = -2*np.pi
x_max = 2*np.pi
resolution = 101
x_vals = np.linspace(x_min, x_max, resolution)
y_upper = np.cos(x_vals)
y_lower = -np.cos(x_vals)
data3 = np.sin(x_vals)
fig = plt.figure(figsize=(80/25.4, 80/25.4)) # figsize is needed for later usage of the plot
ax = fig.subplots(2, 1, sharex=True)
fig.subplots_adjust(hspace=0)
ax[0].plot(x_vals, y_upper, label="data 1")
ax[0].plot(x_vals, y_lower, label="data 2")
ax[1].set_xlim([x_min,x_max])
ax[0].set_ylim([-1.6,1.6])
ax[1].set_ylim([-1.3,1.3])
ax[1].plot(x_vals, data3, ls='-', label="data 3", color='C2')
ax[1].set_xlabel("xaxis")
ax[0].set_ylabel("yaxis 1")
ax[1].set_ylabel("yaxis 2")
ax[0].legend(bbox_to_anchor=(0, 1.02, 1., 0.102), loc='lower left', ncol=2, mode="expand", borderaxespad=0)
fig.suptitle("Title")
fig.tight_layout() # comment this out to see the difference
# fig.savefig('figure.png')
plt.show()
【问题讨论】:
标签: python matplotlib