ipython : get access to current figure()

53,534

Solution 1

plt.gcf() to get current figure

plt.gca() to get current axis

Solution 2

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)

Share:
53,534
sten
Author by

sten

Updated on July 18, 2020

Comments

  • sten
    sten almost 4 years

    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 ?