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?
Use legend() method to avoid overlapping of labels and autopct. To display the figure, use show() method.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With