Graphics arrays and insets

This module defines the classes MultiGraphics and GraphicsArray. The class MultiGraphics is the base class for 2-dimensional graphical objects that are composed of various Graphics objects, arranged in a given canvas. The subclass GraphicsArray is for Graphics objects arranged in a regular array.


  • Eric Gourgoulhon (2019-05-14): initial version, refactoring the class GraphicsArray that was defined in the module graphics.
class sage.plot.multigraphics.GraphicsArray(array)

Bases: sage.plot.multigraphics.MultiGraphics

This class implements 2-dimensional graphical objects that constitute an array of Graphics drawn on a single canvas.

The user interface is through the function graphics_array().


  • array – either a list of lists of Graphics elements (generic case) or a single list of Graphics elements (case of a single-row array)


An array made of four graphics objects:

sage: g1 = plot(sin(x^2), (x, 0, 6), axes_labels=['$x$', '$y$'],
....:           axes=False, frame=True, gridlines='minor')
sage: y = var('y')
sage: g2 = streamline_plot((sin(x), cos(y)), (x,-3,3), (y,-3,3),
....:                      aspect_ratio=1)
sage: g3 = graphs.DodecahedralGraph().plot()
sage: g4 = polar_plot(sin(5*x)^2, (x, 0, 2*pi), color='green',
....:                 fontsize=8) \
....:      + circle((0,0), 0.5, rgbcolor='red', fill=True, alpha=0.1,
....:               legend_label='pink')
sage: g4.set_legend_options(loc='upper right')
sage: G = graphics_array([[g1, g2], [g3, g4]])
sage: G
Graphics Array of size 2 x 2

If one constructs the graphics array from a single list of graphics objects, one obtains a single-row array:

sage: G = graphics_array([g1, g2, g3, g4])
sage: G
Graphics Array of size 1 x 4

We note that the overall aspect ratio of the figure is 4/3 (the default), which makes g1 elongated, while the aspect ratio of g2, which has been specified with the parameter aspect_ratio=1 is preserved. To get a better aspect ratio for the whole figure, one can use the option figsize in the method show():

sage:[8, 3])

We can access to individual elements of the graphics array with the square-bracket operator:

sage: G = graphics_array([[g1, g2], [g3, g4]])  # back to the 2x2 array
sage: print(G)
Graphics Array of size 2 x 2
sage: G[0] is g1
sage: G[1] is g2
sage: G[2] is g3
sage: G[3] is g4

Note that with respect to the square-bracket operator, G is considered as a flattened list of graphics objects, not as an array. For instance, G[0, 1] throws an error:

sage: G[0, 1]  # py3 (error message is slightly different with Python 2)
Traceback (most recent call last):
TypeError: list indices must be integers or slices, not tuple

G[:] returns the full (flattened) list of graphics objects composing G:

sage: G[:]
[Graphics object consisting of 1 graphics primitive,
Graphics object consisting of 1 graphics primitive,
Graphics object consisting of 51 graphics primitives,
Graphics object consisting of 2 graphics primitives]

The total number of Graphics objects composing the array is returned by the function len:

sage: len(G)

The square-bracket operator can be used to replace elements in the array:

sage: G[0] = g4
sage: G
Graphics Array of size 2 x 2

Appends a graphics to the array.

Currently not implemented.


Number of columns of the graphics array.


sage: R = rainbow(6)
sage: L = [plot(x^n, (x,0,1), color=R[n]) for n in range(6)]
sage: G = graphics_array(L, 2, 3)
sage: G.ncols()
sage: graphics_array(L).ncols()

Number of rows of the graphics array.


sage: R = rainbow(6)
sage: L = [plot(x^n, (x,0,1), color=R[n]) for n in range(6)]
sage: G = graphics_array(L, 2, 3)
sage: G.nrows()
sage: graphics_array(L).nrows()
class sage.plot.multigraphics.MultiGraphics

Bases: sage.misc.fast_methods.WithEqualityById, sage.structure.sage_object.SageObject

Base class for objects composed of Graphics objects.

Both the display and the output to a file of MultiGraphics objects are governed by the method save(), which is called by the rich output display manager, via graphics_from_save().

matplotlib(figure=None, figsize=None, **kwds)

Construct or modify a Matplotlib figure by drawing self on it.


  • figure – (default: None) Matplotlib figure (class matplotlib.figure.Figure) on which self is to be displayed; if None, the figure will be created from the parameter figsize
  • figsize – (default: None) width or [width, height] in inches of the Matplotlib figure in case figure is None; if figsize is None, Matplotlib’s default (6.4 x 4.8 inches) is used
  • kwds – options passed to the matplotlib() method of each graphics object constituting self


  • a matplotlib.figure.Figure object; if the argument figure is provided, this is the same object as figure.


Let us consider a GraphicsArray object with 3 elements:

sage: G = graphics_array([plot(sin(x^k), (x, 0, 3))
....:                     for k in range(1, 4)])

If matplotlib() is invoked without any argument, a Matplotlib figure is created and contains the 3 graphics element of the array as 3 Matplotlib Axes:

sage: fig = G.matplotlib()
sage: fig
<Figure size 640x480 with 3 Axes>
sage: type(fig)
<class 'matplotlib.figure.Figure'>

Specifying the figure size (in inches):

sage: G.matplotlib(figsize=(8., 5.))
<Figure size 800x500 with 3 Axes>

If a single number is provided for figsize, it is considered to be the width; the height is then computed according to Matplotlib’s default aspect ratio (4/3):

sage: G.matplotlib(figsize=8.)
<Figure size 800x600 with 3 Axes>

An example of use with a preexisting created figure, created by pyplot:

sage: import matplotlib.pyplot as plt
sage: fig1 = plt.figure(1)
sage: fig1
<Figure size 640x480 with 0 Axes>
sage: fig_out = G.matplotlib(figure=fig1)
sage: fig_out
<Figure size 640x480 with 3 Axes>

Note that the output figure is the same object as the input one:

sage: fig_out is fig1

It has however been modified by G.matplotlib(figure=fig1), which has added 3 new Axes to it.

Another example, with a figure created from scratch, via Matplolib’s Figure:

sage: from matplotlib.figure import Figure
sage: fig2 = Figure()
sage: fig2
<Figure size 640x480 with 0 Axes>
sage: G.matplotlib(figure=fig2)
<Figure size 640x480 with 3 Axes>
sage: fig2
<Figure size 640x480 with 3 Axes>

Draw a 2D plot of this graphics object, which just returns this object since this is already a 2D graphics object.


sage: g1 = plot(cos(20*x)*exp(-2*x), 0, 1)
sage: g2 = plot(2*exp(-30*x) - exp(-3*x), 0, 1)
sage: G = graphics_array([g1, g2], 2, 1)
sage: G.plot() is G
save(filename, figsize=None, **kwds)

Save self to a file, in various formats.


  • filename – (string) the file name; the image format is given by the extension, which can be one of the following:

    • .eps,
    • .pdf,
    • .png,
    • .ps,
    • .sobj (for a Sage object you can load later),
    • .svg,
    • empty extension will be treated as .sobj.
  • figsize – (default: None) width or [width, height] in inches of the Matplotlib figure; if none is provided, Matplotlib’s default (6.4 x 4.8 inches) is used

  • kwds – keyword arguments, like dpi=..., passed to the plotter, see show()


sage: F = tmp_filename(ext='.png')
sage: L = [plot(sin(k*x), (x,-pi,pi)) for k in [1..3]]
sage: G = graphics_array(L)
sage:, dpi=500, axes=False)
save_image(filename=None, *args, **kwds)

Save an image representation of self. The image type is determined by the extension of the filename. For example, this could be .png, .jpg, .gif, .pdf, .svg. Currently this is implemented by calling the save() method of self, passing along all arguments and keywords.


Not all image types are necessarily implemented for all graphics types. See save() for more details.


sage: plots = [[plot(m*cos(x + n*pi/4), (x,0, 2*pi))
....:           for n in range(3)] for m in range(1,3)]
sage: G = graphics_array(plots)
sage: G.save_image(tmp_filename(ext='.png'))

Show self immediately.

This method attempts to display the graphics immediately, without waiting for the currently running code (if any) to return to the command line. Be careful, calling it from within a loop will potentially launch a large number of external viewer programs.


  • dpi – dots per inch
  • figsize – width or [width, height] of the figure, in inches; the default is 6.4 x 4.8 inches
  • axes – boolean; if True, all individual graphics are endowed with axes; if False, all axes are removed (this overrides the axes option set in each graphics)
  • frame – boolean; if True, all individual graphics are drawn with a frame around them; if False, all frames are removed (this overrides the frame option set in each graphics)
  • fontsize – positive integer, the size of fonts for the axes labels (this overrides the fontsize option set in each graphics)


This method does not return anything. Use save() if you want to save the figure as an image.


This draws a graphics array with four trig plots and no axes in any of the plots and a figure width of 4 inches:

sage: G = graphics_array([[plot(sin), plot(cos)],
....:                     [plot(tan), plot(sec)]])
sage:, figsize=4)

Same thing with a frame around each individual graphics:

sage:, frame=True, figsize=4)

Actually, many options are possible; for instance, we may set fontsize and gridlines:

sage:, frame=True, figsize=4, fontsize=8,
....:        gridlines='major')