ipython : get access to current figure()

2019-02-12 07:38发布

I want to add more fine grained grid on a plotted graph. The problem is all of the examples require access to the axis object. I want to add specific grid to already plotted graph (from inside ipython).

How do I gain access to the current figure and axis in ipython ?

2条回答
甜甜的少女心
2楼-- · 2019-02-12 07:53

With the plt? example (assuming ipython --pylab)

In [44]: x=np.arange(0,5,.1)
In [45]: y=np.sin(x)
In [46]: plt.plot(x,y)
Out[46]: [<matplotlib.lines.Line2D at 0xb09418cc>]

displays figure 1; get its handle with:

In [47]: f=plt.figure(1)

In [48]: f
Out[48]: <matplotlib.figure.Figure at 0xb17acb2c>

and a list of its axes:

In [49]: f.axes
Out[49]: [<matplotlib.axes._subplots.AxesSubplot at 0xb091198c>]

turn the grid on for the current (and only) axis:

In [51]: a=f.axes[0]
In [52]: a.grid(True)

I haven't used the plt in a while, so found this stuff by just making the plot and searching the tab completion and ? for likely stuff. I'm pretty sure this is also available in the plt documentation.

Or you can create the figure first, and hang on to its handle

In [53]: fig=plt.figure()
In [55]: ax1=fig.add_subplot(2,1,1)
In [56]: ax2=fig.add_subplot(2,1,2)

In [57]: plt.plot(x,y)
Out[57]: [<matplotlib.lines.Line2D at 0xb12ed5ec>]

In [58]: fig.axes
Out[58]: 
[<matplotlib.axes._subplots.AxesSubplot at 0xb0917e2c>,
 <matplotlib.axes._subplots.AxesSubplot at 0xb17a35cc>]

And there's gcf and gca (get current figure/axis). Same as in MATLAB if my memory is correct.

In [68]: plt.gca()
Out[68]: <matplotlib.axes._subplots.AxesSubplot at 0xb17a35cc>
In [66]: plt.gcf()
Out[66]: <matplotlib.figure.Figure at 0xb091eeec>

(these are used in the sidebar link: Matplotlib.pyplot - Deactivate axes in figure. /Axis of figure overlap with axes of subplot)

查看更多
Summer. ? 凉城
3楼-- · 2019-02-12 08:02

plt.gcf() to get current figure

plt.gca() to get current axis

查看更多
登录 后发表回答