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

允我心安 提交于 2019-12-09 17:12:14

问题


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().

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.

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:


Start ipython with

ipython notebook

rather than

ipython notebook --pylab=inline




回答2:


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)


来源:https://stackoverflow.com/questions/17549713/how-to-have-a-function-return-a-figure-in-python-using-matplotlib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!