mathtext
matplotlib.mathtext
mathtext
is a module for parsing a subset of the TeX math syntax and drawing them to a matplotlib backend.
For a tutorial of its usage see Writing mathematical expressions. This document is primarily concerned with implementation details.
The module uses pyparsing to parse the TeX expression.
The Bakoma distribution of the TeX Computer Modern fonts, and STIX fonts are supported. There is experimental support for using arbitrary fonts, but results may vary without proper tweaking and metrics for those fonts.
-
class matplotlib.mathtext.Accent(c, state)
-
Bases:
matplotlib.mathtext.Char
The font metrics need to be dealt with differently for accents, since they are already offset correctly from the baseline in TrueType fonts.
-
grow()
-
render(x, y)
-
Render the character to the canvas.
-
shrink()
-
-
class matplotlib.mathtext.AutoHeightChar(c, height, depth, state, always=False, factor=None)
-
Bases:
matplotlib.mathtext.Hlist
AutoHeightChar
will create a character as close to the given height and depth as possible. When using a font with multiple height versions of some characters (such as the BaKoMa fonts), the correct glyph will be selected, otherwise this will always just return a scaled version of the glyph.
-
class matplotlib.mathtext.AutoWidthChar(c, width, state, always=False, char_class=
) -
Bases:
matplotlib.mathtext.Hlist
AutoWidthChar
will create a character as close to the given width as possible. When using a font with multiple width versions of some characters (such as the BaKoMa fonts), the correct glyph will be selected, otherwise this will always just return a scaled version of the glyph.
-
class matplotlib.mathtext.BakomaFonts(*args, **kwargs)
-
Bases:
matplotlib.mathtext.TruetypeFonts
Use the Bakoma TrueType fonts for rendering.
Symbols are strewn about a number of font files, each of which has its own proprietary 8-bit encoding.
-
alias = '\\]'
-
get_sized_alternatives_for_symbol(fontname, sym)
-
target = ']'
-
-
class matplotlib.mathtext.Box(width, height, depth)
-
Bases:
matplotlib.mathtext.Node
Represents any node with a physical location.
-
grow()
-
render(x1, y1, x2, y2)
-
shrink()
-
-
class matplotlib.mathtext.Char(c, state)
-
Bases:
matplotlib.mathtext.Node
Represents a single character. Unlike TeX, the font information and metrics are stored with each
Char
to make it easier to lookup the font metrics when needed. Note that TeX boxes have a width, height, and depth, unlike Type1 and Truetype which use a full bounding box and an advance in the x-direction. The metrics must be converted to the TeX way, and the advance (if different from width) must be converted into aKern
node when theChar
is added to its parentHlist
.-
get_kerning(next)
-
Return the amount of kerning between this and the given character. Called when characters are strung together into
Hlist
to createKern
nodes.
-
grow()
-
is_slanted()
-
render(x, y)
-
Render the character to the canvas
-
shrink()
-
-
matplotlib.mathtext.Error(msg)
-
Helper class to raise parser errors.
-
class matplotlib.mathtext.Fil
-
Bases:
matplotlib.mathtext.Glue
-
class matplotlib.mathtext.Fill
-
Bases:
matplotlib.mathtext.Glue
-
class matplotlib.mathtext.Filll
-
Bases:
matplotlib.mathtext.Glue
-
class matplotlib.mathtext.Fonts(default_font_prop, mathtext_backend)
-
Bases:
object
An abstract base class for a system of fonts to use for mathtext.
The class must be able to take symbol keys and font file names and return the character metrics. It also delegates to a backend class to do the actual drawing.
default_font_prop: A
FontProperties
object to use for the default non-math font, or the base font for Unicode (generic) font rendering.mathtext_backend: A subclass of
MathTextBackend
used to delegate the actual rendering.-
destroy()
-
Fix any cyclical references before the object is about to be destroyed.
-
get_kern(font1, fontclass1, sym1, fontsize1, font2, fontclass2, sym2, fontsize2, dpi)
-
Get the kerning distance for font between sym1 and sym2.
fontX: one of the TeX font names:
tt, it, rm, cal, sf, bf or default/regular (non-math)
fontclassX: TODO
symX: a symbol in raw TeX form. e.g., ‘1’, ‘x’ or ‘sigma’
fontsizeX: the fontsize in points
dpi: the current dots-per-inch
-
get_metrics(font, font_class, sym, fontsize, dpi)
-
font: one of the TeX font names:
tt, it, rm, cal, sf, bf or default/regular (non-math)
font_class: TODO
sym: a symbol in raw TeX form. e.g., ‘1’, ‘x’ or ‘sigma’
fontsize: font size in points
dpi: current dots-per-inch
Returns an object with the following attributes:
- advance: The advance distance (in points) of the glyph.
- height: The height of the glyph in points.
- width: The width of the glyph in points.
- xmin, xmax, ymin, ymax - the ink rectangle of the glyph
- iceberg - the distance from the baseline to the top of the glyph. This corresponds to TeX’s definition of “height”.
-
get_results(box)
-
Get the data needed by the backend to render the math expression. The return value is backend-specific.
-
get_sized_alternatives_for_symbol(fontname, sym)
-
Override if your font provides multiple sizes of the same symbol. Should return a list of symbols matching sym in various sizes. The expression renderer will select the most appropriate size for a given situation from this list.
-
get_underline_thickness(font, fontsize, dpi)
-
Get the line thickness that matches the given font. Used as a base unit for drawing lines such as in a fraction or radical.
-
get_used_characters()
-
Get the set of characters that were used in the math expression. Used by backends that need to subset fonts so they know which glyphs to include.
-
get_xheight(font, fontsize, dpi)
-
Get the xheight for the given font and fontsize.
-
render_glyph(ox, oy, facename, font_class, sym, fontsize, dpi)
-
Draw a glyph at
- ox, oy: position
- facename: One of the TeX face names
- font_class:
- sym: TeX symbol name or single character
- fontsize: fontsize in points
- dpi: The dpi to draw at.
-
render_rect_filled(x1, y1, x2, y2)
-
Draw a filled rectangle from (x1, y1) to (x2, y2).
-
set_canvas_size(w, h, d)
-
Set the size of the buffer used to render the math expression. Only really necessary for the bitmap backends.
-
-
class matplotlib.mathtext.Glue(glue_type, copy=False)
-
Bases:
matplotlib.mathtext.Node
Most of the information in this object is stored in the underlying
GlueSpec
class, which is shared between multiple glue objects. (This is a memory optimization which probably doesn’t matter anymore, but it’s easier to stick to what TeX does.)-
grow()
-
shrink()
-
-
class matplotlib.mathtext.GlueSpec(width=0.0, stretch=0.0, stretch_order=0, shrink=0.0, shrink_order=0)
-
Bases:
object
See
Glue
.-
copy()
-
classmethod factory(glue_type)
-
-
class matplotlib.mathtext.HCentered(elements)
-
Bases:
matplotlib.mathtext.Hlist
A convenience class to create an
Hlist
whose contents are centered within its enclosing box.
-
class matplotlib.mathtext.Hbox(width)
-
Bases:
matplotlib.mathtext.Box
A box with only width (zero height and depth).
-
class matplotlib.mathtext.Hlist(elements, w=0.0, m='additional', do_kern=True)
-
Bases:
matplotlib.mathtext.List
A horizontal list of boxes.
-
hpack(w=0.0, m='additional')
-
The main duty of
hpack()
is to compute the dimensions of the resulting boxes, and to adjust the glue if one of those dimensions is pre-specified. The computed sizes normally enclose all of the material inside the new box; but some items may stick out if negative glue is used, if the box is overfull, or if a\vbox
includes other boxes that have been shifted left.- w: specifies a width
- m: is either ‘exactly’ or ‘additional’.
Thus,
hpack(w, 'exactly')
produces a box whose width is exactly w, whilehpack(w, 'additional')
yields a box whose width is the natural width plus w. The default values produce a box with the natural width.
-
kern()
-
Insert
Kern
nodes betweenChar
nodes to set kerning. TheChar
nodes themselves determine the amount of kerning they need (inget_kerning()
), and this function just creates the linked list in the correct way.
-
-
class matplotlib.mathtext.Hrule(state, thickness=None)
-
Bases:
matplotlib.mathtext.Rule
Convenience class to create a horizontal rule.
-
class matplotlib.mathtext.Kern(width)
-
Bases:
matplotlib.mathtext.Node
A
Kern
node has a width field to specify a (normally negative) amount of spacing. This spacing correction appears in horizontal lists between letters like A and V when the font designer said that it looks better to move them closer together or further apart. A kern node can also appear in a vertical list, when its width denotes additional spacing in the vertical direction.-
depth = 0
-
grow()
-
height = 0
-
shrink()
-
-
class matplotlib.mathtext.List(elements)
-
Bases:
matplotlib.mathtext.Box
A list of nodes (either horizontal or vertical).
-
grow()
-
shrink()
-
-
class matplotlib.mathtext.MathTextParser(output)
-
Bases:
object
Create a MathTextParser for the given backend output.
-
get_depth(texstr, dpi=120, fontsize=14)
-
Returns the offset of the baseline from the bottom of the image in pixels.
- texstr
- A valid mathtext string, e.g., r’IQ: $sigma_i=15$’
- dpi
- The dots-per-inch to render the text
- fontsize
- The font size in points
-
parse(s, dpi=72, prop=None)
-
Parse the given math expression s at the given dpi. If prop is provided, it is a
FontProperties
object specifying the “default” font to use in the math expression, used for all non-math text.The results are cached, so multiple calls to
parse()
with the same expression should be fast.
-
to_mask(texstr, dpi=120, fontsize=14)
-
- texstr
- A valid mathtext string, e.g., r’IQ: $sigma_i=15$’
- dpi
- The dots-per-inch to render the text
- fontsize
- The font size in points
Returns a tuple (array, depth)
- array is an NxM uint8 alpha ubyte mask array of rasterized tex.
- depth is the offset of the baseline from the bottom of the image in pixels.
-
to_png(filename, texstr, color='black', dpi=120, fontsize=14)
-
Writes a tex expression to a PNG file.
Returns the offset of the baseline from the bottom of the image in pixels.
- filename
- A writable filename or fileobject
- texstr
- A valid mathtext string, e.g., r’IQ: $sigma_i=15$’
- color
- A valid matplotlib color argument
- dpi
- The dots-per-inch to render the text
- fontsize
- The font size in points
Returns the offset of the baseline from the bottom of the image in pixels.
-
to_rgba(texstr, color='black', dpi=120, fontsize=14)
-
- texstr
- A valid mathtext string, e.g., r’IQ: $sigma_i=15$’
- color
- Any matplotlib color argument
- dpi
- The dots-per-inch to render the text
- fontsize
- The font size in points
Returns a tuple (array, depth)
- array is an NxM uint8 alpha ubyte mask array of rasterized tex.
- depth is the offset of the baseline from the bottom of the image in pixels.
-
-
exception matplotlib.mathtext.MathTextWarning
-
Bases:
Warning
-
class matplotlib.mathtext.MathtextBackend
-
Bases:
object
The base class for the mathtext backend-specific code. The purpose of
MathtextBackend
subclasses is to interface between mathtext and a specific matplotlib graphics backend.Subclasses need to override the following:
And optionally, if you need to use a Freetype hinting style:
-
get_hinting_type()
-
Get the Freetype hinting type to use with this particular backend.
-
get_results(box)
-
Return a backend-specific tuple to return to the backend after all processing is done.
-
render_glyph(ox, oy, info)
-
Draw a glyph described by info to the reference point (ox, oy).
-
render_rect_filled(x1, y1, x2, y2)
-
Draw a filled black rectangle from (x1, y1) to (x2, y2).
-
set_canvas_size(w, h, d)
-
Dimension the drawing canvas
-
-
class matplotlib.mathtext.MathtextBackendAgg
-
Bases:
matplotlib.mathtext.MathtextBackend
Render glyphs and rectangles to an FTImage buffer, which is later transferred to the Agg image by the Agg backend.
-
get_hinting_type()
-
get_results(box, used_characters)
-
render_glyph(ox, oy, info)
-
render_rect_filled(x1, y1, x2, y2)
-
set_canvas_size(w, h, d)
-
-
class matplotlib.mathtext.MathtextBackendBitmap
-
Bases:
matplotlib.mathtext.MathtextBackendAgg
-
get_results(box, used_characters)
-
-
class matplotlib.mathtext.MathtextBackendCairo
-
Bases:
matplotlib.mathtext.MathtextBackend
Store information to write a mathtext rendering to the Cairo backend.
-
get_results(box, used_characters)
-
render_glyph(ox, oy, info)
-
render_rect_filled(x1, y1, x2, y2)
-
-
class matplotlib.mathtext.MathtextBackendPath
-
Bases:
matplotlib.mathtext.MathtextBackend
Store information to write a mathtext rendering to the text path machinery.
-
get_results(box, used_characters)
-
render_glyph(ox, oy, info)
-
render_rect_filled(x1, y1, x2, y2)
-
-
class matplotlib.mathtext.MathtextBackendPdf
-
Bases:
matplotlib.mathtext.MathtextBackend
Store information to write a mathtext rendering to the PDF backend.
-
get_results(box, used_characters)
-
render_glyph(ox, oy, info)
-
render_rect_filled(x1, y1, x2, y2)
-
-
class matplotlib.mathtext.MathtextBackendPs
-
Bases:
matplotlib.mathtext.MathtextBackend
Store information to write a mathtext rendering to the PostScript backend.
-
get_results(box, used_characters)
-
render_glyph(ox, oy, info)
-
render_rect_filled(x1, y1, x2, y2)
-
-
class matplotlib.mathtext.MathtextBackendSvg
-
Bases:
matplotlib.mathtext.MathtextBackend
Store information to write a mathtext rendering to the SVG backend.
-
get_results(box, used_characters)
-
render_glyph(ox, oy, info)
-
render_rect_filled(x1, y1, x2, y2)
-
-
class matplotlib.mathtext.NegFil
-
Bases:
matplotlib.mathtext.Glue
-
class matplotlib.mathtext.NegFill
-
Bases:
matplotlib.mathtext.Glue
-
class matplotlib.mathtext.NegFilll
-
Bases:
matplotlib.mathtext.Glue
-
class matplotlib.mathtext.Node
-
Bases:
object
A node in the TeX box model
-
get_kerning(next)
-
grow()
-
Grows one level larger. There is no limit to how big something can get.
-
render(x, y)
-
shrink()
-
Shrinks one level smaller. There are only three levels of sizes, after which things will no longer get smaller.
-
-
class matplotlib.mathtext.Parser
-
Bases:
object
This is the pyparsing-based parser for math expressions. It actually parses full strings containing math expressions, in that raw text may also appear outside of pairs of
$
.The grammar is based directly on that in TeX, though it cuts a few corners.
-
class State(font_output, font, font_class, fontsize, dpi)
-
Bases:
object
Stores the state of the parser.
States are pushed and popped from a stack as necessary, and the “current” state is always at the top of the stack.
-
copy()
-
font
-
-
Parser.accent(s, loc, toks)
-
Parser.auto_delim(s, loc, toks)
-
Parser.binom(s, loc, toks)
-
Parser.c_over_c(s, loc, toks)
-
Parser.customspace(s, loc, toks)
-
Parser.end_group(s, loc, toks)
-
Parser.font(s, loc, toks)
-
Parser.frac(s, loc, toks)
-
Parser.function(s, loc, toks)
-
Parser.genfrac(s, loc, toks)
-
Parser.get_state()
-
Get the current
State
of the parser.
-
Parser.group(s, loc, toks)
-
Parser.is_dropsub(nucleus)
-
Parser.is_overunder(nucleus)
-
Parser.is_slanted(nucleus)
-
Parser.main(s, loc, toks)
-
Parser.math(s, loc, toks)
-
Parser.math_string(s, loc, toks)
-
Parser.non_math(s, loc, toks)
-
Parser.operatorname(s, loc, toks)
-
Parser.overline(s, loc, toks)
-
Parser.parse(s, fonts_object, fontsize, dpi)
-
Parse expression s using the given fonts_object for output, at the given fontsize and dpi.
Returns the parse tree of
Node
instances.
-
Parser.pop_state()
-
Pop a
State
off of the stack.
-
Parser.push_state()
-
Push a new
State
onto the stack which is just a copy of the current state.
-
Parser.required_group(s, loc, toks)
-
Parser.simple_group(s, loc, toks)
-
Parser.snowflake(s, loc, toks)
-
Parser.space(s, loc, toks)
-
Parser.sqrt(s, loc, toks)
-
Parser.stackrel(s, loc, toks)
-
Parser.start_group(s, loc, toks)
-
Parser.subsuper(s, loc, toks)
-
Parser.symbol(s, loc, toks)
-
Parser.unknown_symbol(s, loc, toks)
-
-
class matplotlib.mathtext.Rule(width, height, depth, state)
-
Bases:
matplotlib.mathtext.Box
A
Rule
node stands for a solid black rectangle; it has width, depth, and height fields just as in anHlist
. However, if any of these dimensions is inf, the actual value will be determined by running the rule up to the boundary of the innermost enclosing box. This is called a “running dimension.” The width is never running in anHlist
; the height and depth are never running in aVlist
.-
render(x, y, w, h)
-
-
class matplotlib.mathtext.Ship
-
Bases:
object
Once the boxes have been set up, this sends them to output. Since boxes can be inside of boxes inside of boxes, the main work of
Ship
is done by two mutually recursive routines,hlist_out()
andvlist_out()
, which traverse theHlist
nodes andVlist
nodes inside of horizontal and vertical boxes. The global variables used in TeX to store state as it processes have become member variables here.-
static clamp(value)
-
hlist_out(box)
-
vlist_out(box)
-
-
class matplotlib.mathtext.SsGlue
-
Bases:
matplotlib.mathtext.Glue
-
class matplotlib.mathtext.StandardPsFonts(default_font_prop)
-
Bases:
matplotlib.mathtext.Fonts
Use the standard postscript fonts for rendering to backend_ps
Unlike the other font classes, BakomaFont and UnicodeFont, this one requires the Ps backend.
-
basepath = '/home/tcaswell/.virtualenvs/dd35/lib/python3.5/site-packages/matplotlib/mpl-data/fonts/afm'
-
fontmap = {'tt': 'pcrr8a', 'sf': 'phvr8a', 'cal': 'pzcmi8a', 'rm': 'pncr8a', None: 'psyr', 'it': 'pncri8a', 'bf': 'pncb8a'}
-
get_kern(font1, fontclass1, sym1, fontsize1, font2, fontclass2, sym2, fontsize2, dpi)
-
get_underline_thickness(font, fontsize, dpi)
-
get_xheight(font, fontsize, dpi)
-
-
class matplotlib.mathtext.StixFonts(*args, **kwargs)
-
Bases:
matplotlib.mathtext.UnicodeFonts
A font handling class for the STIX fonts.
In addition to what UnicodeFonts provides, this class:
- supports “virtual fonts” which are complete alpha numeric character sets with different font styles at special Unicode code points, such as “Blackboard”.
- handles sized alternative characters for the STIXSizeX fonts.
-
cm_fallback = False
-
get_sized_alternatives_for_symbol(fontname, sym)
-
use_cmex = False
-
class matplotlib.mathtext.StixSansFonts(*args, **kwargs)
-
Bases:
matplotlib.mathtext.StixFonts
A font handling class for the STIX fonts (that uses sans-serif characters by default).
-
class matplotlib.mathtext.SubSuperCluster
-
Bases:
matplotlib.mathtext.Hlist
SubSuperCluster
is a sort of hack to get around that fact that this code do a two-pass parse like TeX. This lets us store enough information in the hlist itself, namely the nucleus, sub- and super-script, such that if another script follows that needs to be attached, it can be reconfigured on the fly.
-
class matplotlib.mathtext.TruetypeFonts(default_font_prop, mathtext_backend)
-
Bases:
matplotlib.mathtext.Fonts
A generic base class for all font setups that use Truetype fonts (through FT2Font).
-
class CachedFont(font)
-
Bases:
object
-
TruetypeFonts.destroy()
-
TruetypeFonts.get_kern(font1, fontclass1, sym1, fontsize1, font2, fontclass2, sym2, fontsize2, dpi)
-
TruetypeFonts.get_underline_thickness(font, fontsize, dpi)
-
TruetypeFonts.get_xheight(font, fontsize, dpi)
-
-
class matplotlib.mathtext.UnicodeFonts(*args, **kwargs)
-
Bases:
matplotlib.mathtext.TruetypeFonts
An abstract base class for handling Unicode fonts.
While some reasonably complete Unicode fonts (such as DejaVu) may work in some situations, the only Unicode font I’m aware of with a complete set of math symbols is STIX.
This class will “fallback” on the Bakoma fonts when a required symbol can not be found in the font.
-
get_sized_alternatives_for_symbol(fontname, sym)
-
use_cmex = True
-
-
class matplotlib.mathtext.VCentered(elements)
-
Bases:
matplotlib.mathtext.Hlist
A convenience class to create a
Vlist
whose contents are centered within its enclosing box.
-
class matplotlib.mathtext.Vbox(height, depth)
-
Bases:
matplotlib.mathtext.Box
A box with only height (zero width).
-
class matplotlib.mathtext.Vlist(elements, h=0.0, m='additional')
-
Bases:
matplotlib.mathtext.List
A vertical list of boxes.
-
vpack(h=0.0, m='additional', l=inf)
-
The main duty of
vpack()
is to compute the dimensions of the resulting boxes, and to adjust the glue if one of those dimensions is pre-specified.- h: specifies a height
- m: is either ‘exactly’ or ‘additional’.
- l: a maximum height
Thus,
vpack(h, 'exactly')
produces a box whose height is exactly h, whilevpack(h, 'additional')
yields a box whose height is the natural height plus h. The default values produce a box with the natural width.
-
-
class matplotlib.mathtext.Vrule(state)
-
Bases:
matplotlib.mathtext.Rule
Convenience class to create a vertical rule.
-
matplotlib.mathtext.get_unicode_index(symbol) → integer
-
Return the integer index (from the Unicode table) of symbol. symbol can be a single unicode character, a TeX command (i.e. r’pi’), or a Type1 symbol name (i.e. ‘phi’).
-
matplotlib.mathtext.math_to_image(s, filename_or_obj, prop=None, dpi=None, format=None)
-
Given a math expression, renders it in a closely-clipped bounding box to an image file.
- s
- A math expression. The math portion should be enclosed in dollar signs.
- filename_or_obj
- A filepath or writable file-like object to write the image data to.
- prop
- If provided, a FontProperties() object describing the size and style of the text.
- dpi
- Override the output dpi, otherwise use the default associated with the output format.
- format
- The output format, e.g., ‘svg’, ‘pdf’, ‘ps’ or ‘png’. If not provided, will be deduced from the filename.
-
matplotlib.mathtext.unichr_safe(index)
-
Return the Unicode character corresponding to the index, or the replacement character if this is a narrow build of Python and the requested character is outside the BMP.
© 2012–2016 Matplotlib Development Team. All rights reserved.
Licensed under the Matplotlib License Agreement.
http://matplotlib.org/1.5.3/api/mathtext_api.html