python - 由于 Figsize,x 标签位于我的图形之外

标签 python matplotlib plot

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

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]]

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()

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

我很确定这是因为更改了 figsize 并且似乎它按比例分配了标签空间。请参阅下面的正常 figsize 图: right graph

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

最佳答案

使用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()

enter image description here

更新

根据@TrentonMcKinney的建议,您还可以将 tight_layout=True 作为 plt.figure

的参数传递
plt.figure(figsize=(7, 3), tight_layout=True)

关于python - 由于 Figsize,x 标签位于我的图形之外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70195707/

相关文章:

python - 动态评估 Pandas 公式中的表达式?

python - 遍历 numpy 数组列的所有成对组合

python - 当服务器运行一个长的 lua 脚本时让 redis 客户端等待

Matlab如何填充箭袋箭头

plot - Maxima 2D 图——如何将轴设置为相等

python - 使用python拟合先知模型时出现问题

python matplotlib.pyplot 和 numpy 问题

python - groupby 多个值,并绘制结果

django - 如何在 Elastic Beanstalk 上安装 matplotlib

r - 如何让ggplot线跑到边缘?