You are reading documentation for the unreleased version of Matplotlib. Try searching for the released version of this page instead?
Applications are open for the 2018 John Hunter Matplotlib Summer Fellowship. Apply now!
Version 2.2.2.post1768+g23420a4c1
Fork me on GitHub


A PDF matplotlib backend Author: Jouni K Seppänen <>


alias of matplotlib.backends.backend_pdf.FigureCanvasPdf

class matplotlib.backends.backend_pdf.FigureCanvasPdf(figure)[source]

Bases: matplotlib.backend_bases.FigureCanvasBase

The canvas the figure renders into. Calls the draw and print fig methods, creates the renderers, etc...

figure : matplotlib.figure.Figure

A high-level Figure instance


Render the Figure.

filetypes = {'pdf': 'Portable Document Format'}
fixed_dpi = 72

Get the default savefig file format as specified in rcParam savefig.format. Returned string excludes period. Overridden in backends that only support a single file type.

print_pdf(filename, *, dpi=72, bbox_inches_restore=None, metadata=None, **kwargs)[source]
class matplotlib.backends.backend_pdf.GraphicsContextPdf(file)[source]

Bases: matplotlib.backend_bases.GraphicsContextBase

alpha_cmd(alpha, forced, effective_alphas)[source]
capstyles = {'butt': 0, 'projecting': 2, 'round': 1}
clip_cmd(cliprect, clippath)[source]

Set clip rectangle. Calls self.pop() and self.push().

commands = ((('_cliprect', '_clippath'), <function GraphicsContextPdf.clip_cmd>), (('_alpha', '_forced_alpha', '_effective_alphas'), <function GraphicsContextPdf.alpha_cmd>), (('_capstyle',), <function GraphicsContextPdf.capstyle_cmd>), (('_fillcolor',), <function GraphicsContextPdf.fillcolor_cmd>), (('_joinstyle',), <function GraphicsContextPdf.joinstyle_cmd>), (('_linewidth',), <function GraphicsContextPdf.linewidth_cmd>), (('_dashes',), <function GraphicsContextPdf.dash_cmd>), (('_rgb',), <function GraphicsContextPdf.rgb_cmd>), (('_hatch', '_hatch_color'), <function GraphicsContextPdf.hatch_cmd>))

Copy properties of other into self.


Copy properties of other into self and return PDF commands needed to transform self into other.


Predicate: does the path need to be filled?

An optional argument can be used to specify an alternative _fillcolor, as needed by RendererPdf.draw_markers.


Make sure every pushed graphics state is popped.

hatch_cmd(hatch, hatch_color)[source]
joinstyles = {'bevel': 2, 'miter': 0, 'round': 1}

Return the appropriate pdf operator to cause the path to be stroked, filled, or both.


Predicate: does the path need to be stroked (its outline drawn)? This tests for the various conditions that disable stroking the path, in which case it would presumably be filled.

class matplotlib.backends.backend_pdf.Name(name)[source]

Bases: object

PDF name object.

static hexify(match)[source]
class matplotlib.backends.backend_pdf.Operator(op)[source]

Bases: object

PDF operator object.

class matplotlib.backends.backend_pdf.PdfFile(filename, metadata=None)[source]

Bases: object

PDF file object.

addGouraudTriangles(points, colors)[source]

Return name of an ExtGState that sets alpha to the given value.

beginStream(id, len, extra=None, png=None)[source]

Flush all buffers and free all resources.

createType1Descriptor(t1font, fontfile)[source]

Given a dvi font object, return a name suitable for Op.selectfont. This registers the font information in self.dviFontInfo if not yet registered.

embedTTF(filename, characters)[source]

Embed the TTF font from the named file into the document.


Write out the various deferred objects and the pdf end matter.


Select a font based on fontprop and return a name suitable for Op.selectfont. If fontprop is a string, it will be interpreted as the filename of the font.


Return name of an image XObject representing the given image.

markerObject(path, trans, fill, stroke, lw, joinstyle, capstyle)[source]

Return name of a marker XObject representing the given path.

newPage(width, height)[source]
newTextnote(text, positionRect=[-100, -100, 0, 0])[source]
pathCollectionObject(gc, path, trans, padding, filled, stroked)[source]
static pathOperations(path, transform, clip=None, simplify=None, sketch=None)[source]

Reserve an ID for an indirect object. The name is used for debugging in case we forget to print out the object with writeObject.


Deprecated since version 3.0: The texFontMap function was deprecated in Matplotlib 3.0 and will be removed in 3.2.


Write out the info dictionary, checking it for good form

writeObject(object, contents)[source]
writePath(path, transform, clip=False, sketch=None)[source]

Write out the PDF trailer.


Write out the xref table.

class matplotlib.backends.backend_pdf.PdfPages(filename, keep_empty=True, metadata=None)[source]

Bases: object

A multi-page PDF file.


In reality PdfPages is a thin wrapper around PdfFile, in order to avoid confusion when using savefig() and forgetting the format argument.


>>> import matplotlib.pyplot as plt
>>> # Initialize:
>>> with PdfPages('foo.pdf') as pdf:
...     # As many times as you like, create a figure fig and save it:
...     fig = plt.figure()
...     pdf.savefig(fig)
...     # When no figure is specified the current figure is saved
...     pdf.savefig()

Create a new PdfPages object.

filename : str

Plots using PdfPages.savefig() will be written to a file at this location. The file is opened at once and any older file with the same name is overwritten.

keep_empty : bool, optional

If set to False, then empty pdf files will be deleted automatically when closed.

metadata : dictionary, optional

Information dictionary object (see PDF reference section 10.2.1 'Document Information Dictionary'), e.g.: {'Creator': 'My software', 'Author': 'Me', 'Title': 'Awesome fig'}

The standard keys are 'Title', 'Author', 'Subject', 'Keywords', 'Creator', 'Producer', 'CreationDate', 'ModDate', and 'Trapped'. Values have been predefined for 'Creator', 'Producer' and 'CreationDate'. They can be removed by setting them to None.

attach_note(text, positionRect=[-100, -100, 0, 0])[source]

Add a new text note to the page to be saved next. The optional positionRect specifies the position of the new note on the page. It is outside the page per default to make sure it is invisible on printouts.


Finalize this object, making the underlying file a complete PDF file.


Returns the current number of pages in the multipage pdf file.


Return a modifiable information dictionary object (see PDF reference section 10.2.1 'Document Information Dictionary').

savefig(figure=None, **kwargs)[source]

Saves a Figure to this file as a new page.

Any other keyword arguments are passed to savefig().

figure : Figure or int, optional

Specifies what figure is saved to file. If not specified, the active figure is saved. If a Figure instance is provided, this figure is saved. If an int is specified, the figure instance to save is looked up by number.

class matplotlib.backends.backend_pdf.Reference(id)[source]

Bases: object

PDF reference object. Use PdfFile.reserveObject() to create References.

write(contents, file)[source]
class matplotlib.backends.backend_pdf.RendererPdf(file, image_dpi, height, width)[source]

Bases: matplotlib.backend_bases.RendererBase

afm_font_cache = {}
check_gc(gc, fillcolor=None)[source]
draw_gouraud_triangle(gc, points, colors, trans)[source]

Draw a Gouraud-shaded triangle.

points : array_like, shape=(3, 2)

Array of (x, y) points for the triangle.

colors : array_like, shape=(3, 4)

RGBA colors for each point of the triangle.

transform : matplotlib.transforms.Transform

An affine transform to apply to the points.

draw_gouraud_triangles(gc, points, colors, trans)[source]

Draws a series of Gouraud triangles.

points : array_like, shape=(N, 3, 2)

Array of N (x, y) points for the triangles.

colors : array_like, shape=(N, 3, 4)

Array of N RGBA colors for each point of the triangles.

transform : matplotlib.transforms.Transform

An affine transform to apply to the points.

draw_image(gc, x, y, im, transform=None)[source]

Draw an RGBA image.

gc : GraphicsContextBase

a graphics context with clipping information.

x : scalar

the distance in physical units (i.e., dots or pixels) from the left hand side of the canvas.

y : scalar

the distance in physical units (i.e., dots or pixels) from the bottom side of the canvas.

im : array_like, shape=(N, M, 4), dtype=np.uint8

An array of RGBA pixels.

transform : matplotlib.transforms.Affine2DBase

If and only if the concrete backend is written such that option_scale_image() returns True, an affine transformation may be passed to draw_image(). It takes the form of a Affine2DBase instance. The translation vector of the transformation is given in physical units (i.e., dots or pixels). Note that the transformation does not override x and y, and has to be applied before translating the result by x and y (this can be accomplished by adding x and y to the translation vector defined by transform).

draw_markers(gc, marker_path, marker_trans, path, trans, rgbFace=None)[source]

Draws a marker at each of the vertices in path. This includes all vertices, including control points on curves. To avoid that behavior, those vertices should be removed before calling this function.

This provides a fallback implementation of draw_markers that makes multiple calls to draw_path(). Some backends may want to override this method in order to draw the marker only once and reuse it multiple times.

gc : GraphicsContextBase

The graphics context

marker_trans : matplotlib.transforms.Transform

An affine transform applied to the marker.

trans : matplotlib.transforms.Transform

An affine transform applied to the path.

draw_mathtext(gc, x, y, s, prop, angle)[source]
draw_path(gc, path, transform, rgbFace=None)[source]

Draws a Path instance using the given affine transform.

draw_path_collection(gc, master_transform, paths, all_transforms, offsets, offsetTrans, facecolors, edgecolors, linewidths, linestyles, antialiaseds, urls, offset_position)[source]

Draws a collection of paths selecting drawing properties from the lists facecolors, edgecolors, linewidths, linestyles and antialiaseds. offsets is a list of offsets to apply to each of the paths. The offsets in offsets are first transformed by offsetTrans before being applied. offset_position may be either "screen" or "data" depending on the space that the offsets are in.

This provides a fallback implementation of draw_path_collection() that makes multiple calls to draw_path(). Some backends may want to override this in order to render each set of path data only once, and then reference that path multiple times with the different offsets, colors, styles etc. The generator methods _iter_collection_raw_paths() and _iter_collection() are provided to help with (and standardize) the implementation across backends. It is highly recommended to use those generators, so that changes to the behavior of draw_path_collection() can be made globally.

draw_tex(gc, x, y, s, prop, angle, ismath='TeX!', mtext=None)[source]
draw_text(gc, x, y, s, prop, angle, ismath=False, mtext=None)[source]

Draw the text instance

gc : GraphicsContextBase

the graphics context

x : scalar

the x location of the text in display coords

y : scalar

the y location of the text baseline in display coords

s : str

the text string

prop : matplotlib.font_manager.FontProperties

font properties

angle : scalar

the rotation angle in degrees

mtext : matplotlib.text.Text

the original text object to be rendered


backend implementers note

When you are trying to determine if you have gotten your bounding box right (which is what enables the text layout/alignment to work properly), it helps to change the line in

if 0: bbox_artist(self, renderer)

to if 1, and then the actual bounding box will be plotted along with your text.

encode_string(s, fonttype)[source]

Return true if y small numbers are top for renderer Is used for drawing text (matplotlib.text) and images (matplotlib.image) only


return the canvas width and height in display coords


Get the factor by which to magnify images passed to draw_image(). Allows a backend to have images at a different resolution to other artists.

get_text_width_height_descent(s, prop, ismath)[source]

Get the width, height, and descent (offset from the bottom to the baseline), in display coords, of the string s with FontProperties prop


Return an instance of a GraphicsContextBase


return whether to generate a composite image from multiple images on a set of axes


pdf backend support arbitrary scaling of image.

track_characters(font, s)[source]

Keeps track of which characters are required from each font.

class matplotlib.backends.backend_pdf.Stream(id, len, file, extra=None, png=None)[source]

Bases: object

PDF stream object.

This has no pdfRepr method. Instead, call begin(), then output the contents of the stream by calling write(), and finally call end().

id: object id of stream; len: an unused Reference object for the length of the stream, or None (to use a memory buffer); file: a PdfFile; extra: a dictionary of extra key-value pairs to include in the stream header; png: if the data is already png compressed, the decode parameters


Finalize stream.


Write some data on the stream.

class matplotlib.backends.backend_pdf.Verbatim(x)[source]

Bases: object

Store verbatim PDF command content for later inclusion in the stream.

matplotlib.backends.backend_pdf.fill(strings, linelen=75)[source]

Make one string from sequence of strings, with whitespace in between. The whitespace is chosen to form lines of at most linelen characters, if possible.


Map Python objects to PDF syntax.