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

Time:09-29

When plotting successive charts in a single Python script, plt.clf() does not reverse the effect of plt.gcf().subplots_adjust(bottom=0.5). The first chart is adjusted to allow x-axis labels more display space, but this change persists into the second chart. How can one plot the second chart in dist() to look normal? Even calling sns.set() or re-importing plt in the function dist() or after box_adj() is called didn't seem to fix the issue.

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

CodePudding user response:

plt.clf() only clears the contents of the plot figure, leaving the figure intact. Its whitespace settings and its size don't change.

You could replace plt.clf() with plt.close() to fully close the figure (matplotlib will automatically create a new one when needed). Alternatively, you can explicitly call fig = plt.figure(...) or fig, ax = plt.subplots(...) to create a new figure with default settings.

  • Related