Taking control of rendering of artists

Faster rendering by using blitting

This module is derived from the code for the matplotlib tutorial on rendering.

Blitting is a standard technique in raster graphics that, in the context of Matplotlib, can be used to (drastically) improve performance of interactive figures. For example, the animation and widgets modules use blitting internally. Here, we demonstrate how to implement your own blitting, outside of these classes.

Blitting speeds up repetitive drawing by rendering all non-changing graphic elements into a background image once. Then, for every draw, only the changing elements need to be drawn onto this background. For example, if the limits of an Axes have not changed, we can render the empty Axes including all ticks and labels once, and only draw the changing data later.

The strategy is

  • Prepare the constant background:

    • Draw the figure, but exclude all artists that you want to animate by marking them as animated (see .Artist.set_animated).

    • Save a copy of the RBGA buffer.

  • Render the individual images:

    • Restore the copy of the RGBA buffer.

    • Redraw the animated artists using .Axes.draw_artist / .Figure.draw_artist.

    • Show the resulting image on the screen.

One consequence of this procedure is that your animated artists are always drawn on top of the static artists.

Not all backends support blitting. You can check if a given canvas does via the .FigureCanvasBase.supports_blit property.

Warning

This code does not work with the OSX backend (but does work with other GUI backends on mac).

Update: this code now seems to work with the default OSX backend.

Minimal example

We can use the .FigureCanvasAgg methods ~.FigureCanvasAgg.copy_from_bbox and ~.FigureCanvasAgg.restore_region in conjunction with setting animated=True on our artist to implement a minimal example that uses blitting to accelerate rendering