英文:
How to prevent jupyter notebook from plotting figure returned by a function
问题
我有一个简单的函数:
def return_fig():
fig = plt.figure()
plt.plot([1,2,3,4,5],[1,2,3,4,5])
return fig
在Jupyter笔记本中,我定义了这个函数并导入了matplotlib.pyplot:
import matplotlib.pyplot as plt
在一个新的单元格中,我有:
figure = return_fig()
当我执行该单元格时,图形会立即显示。然而,我只想要图形对象存在,并且稍后可以使用 plt.show()
来显示它。这是在常规Python脚本中发生的情况,但不适用于Jupyter笔记本。我漏掉了什么?
英文:
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?
答案1
得分: 1
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:
英文:
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:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论