1

I am using ipython notebook and trying to use the following function to export seaborn distplots. It works just fine if I call the function and execute with only one variable at a time. If I call the function in a loop, it continues to build on top of the distplot from the previous function call.

My desired output would be for the function to output a new displot every time it is called in a loop. Is there a way to force evaluation or a new distplot?

def graph_extraversion (x):


    file_name = "extraversion_" + str(x) + ".png"
    sns_plot = sns.distplot(Personalities[Personalities.labels1 ==x].extraversion)
    sns_plot = sns.distplot(df.extraversion)
    fig = sns_plot.get_figure()
    fig.savefig(file_name)
    new_stat = Personalities[Personalities.labels1 ==x].extraversion.describe()
    extraversion_drift = extraversion_median - new_stat[1]
    drift = extraversion_drift / extraversion_std
    if (drift >= 1) | (drift <= -1):
        return "1 std deviation or more"
    else:
        return "Less than one std deviation"

This what is what the distplot looks like after one call

enter image description here

This is two calls later in a loop.

enter image description here

Again this works just fine with a single call and execution but when looped it keeps building.

2
  • You may want to look at stackoverflow.com/questions/23969619/…. Commented Jul 11, 2016 at 11:52
  • I looked at the posting, but is there a way to return the function to the caller and instantiate a new figure in a loop. Commented Jul 14, 2016 at 1:54

1 Answer 1

1

So this has to do with matplotlib and closing figures.

additional code required is an import:

import matplotlib.pyplot as plt

Then at the end of the func:

plt.close(fig)

This should help with any looping with both seaborn and matplotlib

Sign up to request clarification or add additional context in comments.

1 Comment

No additional import needed, just fig.close(). Using the figure object seems to be the more acceptable way to do this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.