如何让函数在python中返回一个数字(使用matplotlib)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17549713/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:29:54  来源:igfitidea点击:

How to have a function return a figure in python (using matplotlib)?

pythonmatplotlibipython-notebook

提问by siva82kb

Assume that I have some data, and I want to create a plot of this data by passing it to a custom plotting function (myplot()). I am using the matplotlib's modules in myplot().

假设我有一些数据,我想通过将这些数据传递给自定义绘图函数 (myplot()) 来创建该数据的绘图。我在 myplot() 中使用 matplotlib 的模块。

I would like myplot() to return the handle to a figure, and not plot display the plot when I call this function. Here is a sample code and output from iPython.

我希望 myplot() 将句柄返回到图形,并且在调用此函数时不绘制显示图。这是 iPython 的示例代码和输出。

enter image description here

在此处输入图片说明

I have two questions regarding this:

关于这个我有两个问题:

  1. Why do I still see a plot, even though I am assigning the output of myplot() to f?
  2. What do I need to supress this plot when I am assigning the output of myplot() to a variable?
  1. 为什么我仍然看到一个情节,即使我将 myplot() 的输出分配给 f?
  2. 当我将 myplot() 的输出分配给一个变量时,我需要什么来抑制这个图?

采纳答案by unutbu

Start ipython with

启动 ipython

ipython notebook

ipython notebook

rather than

而不是

ipython notebook --pylab=inline

ipython notebook --pylab=inline

enter image description here

在此处输入图片说明

回答by ala

If you do not want to start the whole notebook in non-inline-modus you can just use the following code:

如果您不想以非内联模式启动整个笔记本,您可以使用以下代码:

%config InlineBackend.close_figures = False

def myplot(t,x):
    fig = figure()
    x = plot(t,x)
    fig.savefig('plot.png') # This is just to show the figure is still generated
    return fig

t = arange(0,6,0.01)
x = sin(t)

f = myplot(t,x)