Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib: user defined plot function print twice

I want to create a plot with a function, it will return a fig so later on I can redisplay it when needed.

The function goes 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')
    return fig

If I run simple_plot(), it would print the plot twice, like this:

enter image description here

Notice: if I run fig = simple_plot(), it will only print once, and I can use fig to reproduce the plot later in Ipython Notebook

  1. How can I make it only print once if I run simple_plot()?

  2. I'm not sure if I defined the function correctly, what would be a good way to define a function to make plot?

like image 806
cqcn1991 Avatar asked Feb 16 '16 03:02

cqcn1991


People also ask

How do I stop matplotlib overlapping?

Use legend() method to avoid overlapping of labels and autopct. To display the figure, use show() method.

How do I create a double subplot in matplotlib?

To create multiple plots use matplotlib. pyplot. subplots method which returns the figure along with Axes object or array of Axes object. nrows, ncols attributes of subplots() method determine the number of rows and columns of the subplot grid.


Video Answer


1 Answers

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.

like image 186
foglerit Avatar answered Nov 02 '22 00:11

foglerit