Matplotlib: custom print function print twice

I want to create a graph with a function, it will return the fig so later, I can re-display it when necessary.

The function is performed as follows:

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 will print the graph twice, for example:

enter image description here

Please note: if I run fig = simple_plot() , it will print only once, and I can use fig to play the graph later on in the Ipython Notebook

  • How can I do this only once if I run simple_plot() ?

  • I'm not sure if I defined the function correctly, which would be a good way to define a function to create a graph?

+6
source share
3 answers

This is a side effect of the automatic display feature in Jupyter Notebooks. Whenever you call plt.plot() , it calls up a graph display. But also, when the shape object is referenced as the last cell operator, another display is triggered. This last screen does not start when the last statement in the cell is an assignment ( fig = simple_plot() ), and therefore you do not see the second graph.

To prevent the second graph from appearing (or automatically displaying any source link), simply add a semicolon at the end of the last statement in the cell. For instance. call simple_plot(); will display only one graph.

+6
source

Delete return statement

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

You can also save the return statement, but save the return value in a variable and draw the shape again by doing fig .

enter image description here

+1
source

Just add plt.close() to return , for example:

 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 
0
source

All Articles