Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

For some time, I was looking for a way how to generate several sage Graphics() objects and plot them on a matplotlib canvas in an arbitrary arrangement, using .matplotlib() function. It went out not being straightforward. I decided that the solution I've found may be interesting for others as well. The following code produces a plot with a nice inset:

#make some graphs
x=var('x')
g=plot(sin(x))
g_ins=plot(cos(x))
# plot main figure
from matplotlib.figure import Figure
figure = Figure()
main_plot = figure.add_axes((0.2,0.2,0.7,0.7))
g.matplotlib('a.svg', figure=figure, sub=main_plot)
# plot an inset
inset = figure.add_axes((0.6,0.2,0.3,0.3))
g_ins.matplotlib('a.svg', figure=figure, sub=inset)
# display graph (note that only single sage Graphics object has to be saved )
g_ins.save('a.svg', figure=figure, sub=inset)

For some time, I was looking for a way how to generate several sage Graphics() objects and plot them on a matplotlib canvas in an arbitrary arrangement, using .matplotlib() function. It went out not being straightforward. I decided that the solution I've found may be interesting for others as well. The following code produces a plot with a nice inset:

#make some graphs
x=var('x')
g=plot(sin(x))
g_ins=plot(cos(x))
# plot main figure
from matplotlib.figure import Figure
figure = Figure()
Figure() # you may set the size here
main_plot = figure.add_axes((0.2,0.2,0.7,0.7))
g.matplotlib('a.svg', figure=figure, sub=main_plot)
# plot an inset
inset = figure.add_axes((0.6,0.2,0.3,0.3))
g_ins.matplotlib('a.svg', figure=figure, sub=inset)
# display graph (note that only single sage Graphics object has to be saved )
g_ins.save('a.svg', figure=figure, sub=inset)

UPD: if figures are drawn strangely, add

aspect_ratio='automatic'

to matplotlib() parameters. By default it is 1.0, which may be undesired.

Also, you may want to draw the figure itself, not by Graphics().save() function. Replace the last line with the following:

from matplotlib.backends.backend_agg import FigureCanvasAgg
figure.set_canvas(FigureCanvasAgg(figure)) 
figure.savefig('a.svg')