如何防止Jupyter Notebook绘制函数返回的图形。

huangapple go评论56阅读模式
英文:

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:

如何防止Jupyter Notebook绘制函数返回的图形。

英文:

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:

如何防止Jupyter Notebook绘制函数返回的图形。

huangapple
  • 本文由 发表于 2023年2月18日 04:17:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75488898.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定