绘制和保存多个图表时撤消 plt.gcf().subplots_adjust

Undo plt.gcf().subplots_adjust when plotting and saving more than one chart

在单个 Python 脚本中绘制连续图表时,plt.clf() 不会反转 plt.gcf().subplots_adjust(bottom=0.5) 的效果。第一个图表进行了调整以允许更多显示 x 轴标签 space,但此更改仍然存在于第二个图表中。如何绘制 dist() 中的第二张图表看起来很正常?即使在函数 dist() 中调用 sns.set() 或重新导入 plt 或在调用 box_adj() 之后似乎也无法解决问题。

import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

def box_adj():
    tips = sns.load_dataset("tips")
    ax = sns.boxplot(x="day", y="total_bill", hue="smoker",
                 data=tips, palette="Set3")
    plt.gcf().subplots_adjust(bottom=0.5)
    plt.savefig('box.png')
    plt.clf()

def dist():
    ax = sns.distplot(np.random.randn(1000), kde=False)
    plt.savefig('dist.png')
    plt.clf()

if __name__ == "__main__":
    box_adj()
    dist()

plt.clf() 只清除绘图的内容,保持图形完好无损。它的空白设置和大小不会改变。

您可以将 plt.clf() 替换为 plt.close() 以完全关闭图形(matplotlib 会在需要时自动创建一个新图形)。或者,您可以显式调用 fig = plt.figure(...)fig, ax = plt.subplots(...) 以使用默认设置创建新图形。