Hi all, There has been some recent discussion about perhaps
> improving the OO interface. So Here's a question:
> How do I save an AGG figure with the OO interface?
Hi Chris,
Here is a canonical script to create an Agg canvas/figure and save it
using the pure OO interface. The distinction between the figure and
the canvas was made to fully separate the front end from the backend.
The Figure is the abstract object that stores all the information
about the figure, the canvas is where the ink goes. I agree there
could be some changes to the interface to make this easier, but here
the pure OO way:
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
fig = Figure()
canvas = FigureCanvas(fig)
ax = fig.add_subplot(111)
ax.plot([1,2,3])
ax.set_title('hi mom')
ax.grid(True)
ax.set_xlabel('time')
ax.set_ylabel('volts')
canvas.print_figure('test')
> For example:
>>>> fig = pylab.figure() ax = fig.add_subplot(1,1,1)
>>>> ax.plot(range(10), pylab.sin(range(10)))
> Now how do I save it as a PNG? I can do:
>>>> pylab.savefig("test.png")
> But then that is the interface I'm trying to get away from.
Hmm, I don't see the logic of being willing to use some pylab commands
(pylab.figure) but not others (pylab.savefig). But, if you really
hate savefig, you can call print_figure by getting your hands on the
current canvas
import matplotlib
matplotlib.use('Agg')
import pylab
fig = pylab.figure()
ax = fig.add_subplot(111)
ax.plot([1,2,3])
manager = pylab.get_current_fig_manager()
manager.canvas.print_figure('test')
Kind of awkward. This is basically what savefig does.
> Another option would be:
>>>> fig.savefig
> But that's not there either.
As we discussed earlier, it might be useful for the figure to store a
ref to it's canvas, then we could define fig.savefig which forwards
the call to canvas.print_figure. Would make for a cleaner interface
for folks who love '.'
JDH