How to prevent jupyter notebook from plotting figure returned by a function
Question:
I have a simple function:
def return_fig():
fig = plt.figure()
plt.plot([1,2,3,4,5],[1,2,3,4,5])
return fig
In a jupyter notebook, I define this function and
import matplotlib.pyplot as plt
In a new cell, I have
figure = return_fig()
When I execute the cell, the figure gets shown immediately. However, I just want the figure object to exist, and to be able to show it with plt.show()
later on. This is what happens within a regular python script, but not within a jupyter notebook. What am I missing?
Answers:
Maybe plt.close()
helps.
def return_fig():
fig = plt.figure()
plt.plot([1,2,3,4,5],[1,2,3,4,5])
plt.close(fig)
return fig
Run:
>>> figure = return_fig()
>>> figure
Output:
I have a simple function:
def return_fig():
fig = plt.figure()
plt.plot([1,2,3,4,5],[1,2,3,4,5])
return fig
In a jupyter notebook, I define this function and
import matplotlib.pyplot as plt
In a new cell, I have
figure = return_fig()
When I execute the cell, the figure gets shown immediately. However, I just want the figure object to exist, and to be able to show it with plt.show()
later on. This is what happens within a regular python script, but not within a jupyter notebook. What am I missing?
Maybe plt.close()
helps.
def return_fig():
fig = plt.figure()
plt.plot([1,2,3,4,5],[1,2,3,4,5])
plt.close(fig)
return fig
Run:
>>> figure = return_fig()
>>> figure
Output: