Issue
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:
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
How can I make it only print once if I run
simple_plot()
?I'm not sure if I defined the function correctly, what would be a good way to define a function to make plot?
Solution
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.
Answered By - foglerit
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.