如何让函数在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
How to have a function return a figure in python (using matplotlib)?
提问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 的示例代码和输出。
I have two questions regarding this:
关于这个我有两个问题:
- Why do I still see a plot, even though I am assigning the output of myplot() to f?
- What do I need to supress this plot when I am assigning the output of myplot() to a variable?
- 为什么我仍然看到一个情节,即使我将 myplot() 的输出分配给 f?
- 当我将 myplot() 的输出分配给一个变量时,我需要什么来抑制这个图?
采纳答案by unutbu
Start ipython with
启动 ipython
ipython notebook
ipython notebook
rather than
而不是
ipython notebook --pylab=inline
ipython notebook --pylab=inline
回答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)