Matplotlib: user defined plot function print twice

This is a side effect of the automatic display functionality of the Jupyter Notebooks. Whenever you call plt.plot() it triggers the display of the plot. But also, Jupyter displays the return value of the last line of every cell, so if the figure object is referenced as the last statement of the cell, another display is triggered. If the last statement of the cell is an assignment (fig = simple_plot()), the return value is None and thus a second display is not triggered and you don't get the second plot.


Just add plt.close() before return, like this:

def simple_plot(ax = None):
    if ax is None:
        fig, ax = plt.subplots()
    a = [1,2,3,4]
    b = [3,4,5,6]
    plt.plot(a, b,'-', color='black')
    plt.close()
    return fig

Remove your return statement

Ipython Notebook is plotting once when you execute plt.plot(a, b,'-', color='black') and a second time when you return your fig object to the console.

You could as well keep the return statement, but store the returned value into a variable and plot the figure again just by executing fig.

enter image description here