首页 > 解决方案 > 绘制和保存多个图表时撤消 plt.gcf().subplots_adjust

问题描述

在单个 Python 脚本中绘制连续图表时,plt.clf()不会反转plt.gcf().subplots_adjust(bottom=0.5). 第一个图表进行了调整以允许 x 轴标签有更多的显示空间,但此更改持续到第二个图表。如何绘制第二张图表以dist()使其看起来正常?即使在函数中或调用之后调用sns.set()或重新导入似乎也无法解决问题。pltdist()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()

标签: matplotlibseaborndata-visualization

解决方案


plt.clf()只清除情节图的内容,使图保持原样。它的空白设置和大小不会改变。

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


推荐阅读