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.

Benny Baysinger
  • 70
  • 1
  • 10
  • You may want to look at http://stackoverflow.com/questions/23969619/plotting-with-seaborn-using-the-matplotlib-object-oriented-interface. – mwaskom Jul 11 '16 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. – Benny Baysinger Jul 14 '16 at 01:54

1 Answers1

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

Benny Baysinger
  • 70
  • 1
  • 10
  • 1
    No additional import needed, just `fig.close()`. Using the figure object seems to be the more acceptable way to do this. – pbreach Jul 28 '16 at 05:20