由于 figsize,x 标签在我的图形之外

x label is outside of my figure because of figsize

我正在使用以下代码构建一个简单的图形:

    plt.figure(figsize=(7, 3))
    plt.plot(idl_t, idl_q, color="blue", lw=2)
    plt.plot(dsc_t, dsc_q, color="red", lw=2)
    plt.plot(cha_t, cha_q, color="green", lw=2)
    plt.xlabel("Time (hour)")
    plt.show()

输入数据如下:

    idl_t, idl_q = [[0, 20], [8, 24]], [[100, 100], [100, 100]]
    dsc_t, dsc_q = [[8, 14], [12, 18]], [[100, 100], [5, 5]]
    cha_t, cha_q = [[12, 18], [14, 20]], [[5, 5], [100, 100]]

但是,代码以某种方式剪切了图上的 x 标签,如下所示:

我很确定这是因为更改了 figsize 并且它似乎按比例分配了标签 space。正常见下图figsize

如何使用不同的 figsizexlabel 保留足够的 space?它实际上应该是这样的吗,因为它对我来说似乎是一个错误?

非常感谢您的建议!

编辑 1:

谢谢大家的回复。虽然我选择 tight_layout 作为更好的解决方案,但我绝对建议您使用 Jody Klymak 提出的方法。请在下面的答案中找到他的实现!

使用plt.tight_layout

plt.figure(figsize=(7, 3), )
plt.plot(idl_t, idl_q, color="blue", lw=2)
plt.plot(dsc_t, dsc_q, color="red", lw=2)
plt.plot(cha_t, cha_q, color="green", lw=2)
plt.xlabel("Time (hour)")
plt.tight_layout()  # <- HERE
plt.show()

使用constrained_layout。它比 tight_layout 更灵活(通常):

import matplotlib.pyplot as plt 

idl_t, idl_q = [[0, 20], [8, 24]], [[100, 100], [100, 100]]
dsc_t, dsc_q = [[8, 14], [12, 18]], [[100, 100], [5, 5]]
cha_t, cha_q = [[12, 18], [14, 20]], [[5, 5], [100, 100]]

fig, ax = plt.subplots(figsize=(7, 3), constrained_layout=True)
ax.plot(idl_t, idl_q, color="blue", lw=2)
ax.plot(dsc_t, dsc_q, color="red", lw=2)
ax.plot(cha_t, cha_q, color="green", lw=2)
ax.set_xlabel("Time (hour)")
plt.show()