Benny Baysinger Benny Baysinger - 1 year ago 430
Python Question

seaborn distplot loop lazy evaluation

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

Answer Source

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:


This should help with any looping with both seaborn and matplotlib

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download