1

A figure generated with seaborn is being visualized, even without f.show().

I want the figure to be only visualized when i call it.

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

def plot_kde_x (x):
    sns.set(style="ticks")
    
    f, (ax_box, ax_hist) = plt.subplots(2, sharex=True, 
                                        gridspec_kw={"height_ratios": (.15, .85)})

    sns.boxplot(x, ax=ax_box)
    sns.kdeplot(x, ax=ax_hist)

    ax_box.set(yticks=[])
    sns.despine(ax=ax_hist)
    sns.despine(ax=ax_box, left=True)
    return f 


x = np.random.randint(1,10,100)
# figure should not be displayed
f = plot_kde_x(x)

OUT, figure still displayed
enter image description here

Leo
  • 1,176
  • 1
  • 13
  • 33

2 Answers2

2

Your problem occurs because matplotlib is using the %matplotlib inline backend automatically. This automatically creates the plot and embeds it in the Jupyter document.

You can temporarily disable/enable the inline creation with plt.ioff() and plt.ion(). Note that f.show() won't work with the inline-backend, but you can simply call f to see the plot.

Here is a full working example:

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

def plot_kde_x (x):
    plt.ioff()
    sns.set(style="ticks")
    
    f, (ax_box, ax_hist) = plt.subplots(2, sharex=True, 
                                        gridspec_kw={"height_ratios": (.15, .85)})

    sns.boxplot(x, ax=ax_box)
    sns.kdeplot(x, ax=ax_hist)

    ax_box.set(yticks=[])
    sns.despine(ax=ax_hist)
    sns.despine(ax=ax_box, left=True)
    plt.ion()
    return f


x = np.random.randint(1,10,100)
# figure should not be displayed
f = plot_kde_x(x)
f
ffrosch
  • 899
  • 6
  • 15
0

If you are using jupyter, the plot is shown twice because plot_kde_x(x) returns the figure.

Either remove the return, or, if you still want to be able to catch the figure object, add ; after the function:

plot_kde_x(x);

Or assign to a variable:

f = plot_kde_x(x)
mozway
  • 194,879
  • 13
  • 39
  • 75
  • thanks, is there a way to stop the first display (while it is being created)? if i do f = plot_kde_x(x), I would like it to display 0 times, just like if i used plotly – Leo Feb 02 '23 at 13:05
  • I have edited for clairty, makitn the question "never visualize the figure unsless f.show() is caled – Leo Feb 02 '23 at 13:08