matplotlib.font_manager#

A module for finding, managing, and using fonts across platforms.

This module provides a singleFontManager instance,fontManager, that canbe shared across backends and platforms. Thefindfontfunction returns the best TrueType (TTF) font file in the local orsystem font path that matches the specifiedFontPropertiesinstance. TheFontManager also handles Adobe Font Metrics(AFM) font files for use by the PostScript backend.TheFontManager.addfont function adds a custom font from a file withoutinstalling it into your operating system.

The design is based on theW3C Cascading Style Sheet, Level 1 (CSS1)font specification.Future versions may implement the Level 2 or 2.1 specifications.

classmatplotlib.font_manager.FontManager(size=None,weight='normal')[source]#

Bases:object

On import, theFontManager singleton instance creates a list of ttf andafm fonts and caches theirFontProperties. TheFontManager.findfontmethod does a nearest neighbor search to find the font that most closelymatches the specification. If no good enough match is found, the defaultfont is returned.

Fonts added with theFontManager.addfont method will not persist in thecache; therefore,addfont will need to be called every time Matplotlib isimported. This method should only be used if and when a font cannot beinstalled on your operating system by other means.

Notes

TheFontManager.addfont method must be called on the globalFontManagerinstance.

Example usage:

importmatplotlib.pyplotaspltfrommatplotlibimportfont_managerfont_dirs=["/resources/fonts"]# The path to the custom font file.font_files=font_manager.findSystemFonts(fontpaths=font_dirs)forfont_fileinfont_files:font_manager.fontManager.addfont(font_file)
addfont(path)[source]#

Cache the properties of the font atpath to make it available to theFontManager. The type of font is inferred from the path suffix.

Parameters:
pathstr or path-like

Notes

This method is useful for adding a custom font without installing it inyour operating system. See theFontManager singleton instance forusage and caveats about this function.

propertydefaultFont#
findfont(prop,fontext='ttf',directory=None,fallback_to_default=True,rebuild_if_missing=True)[source]#

Find the path to the font file most closely matching the given font properties.

Parameters:
propstr orFontProperties

The font properties to search for. This can be either aFontProperties object or a string defining afontconfig patterns.

fontext{'ttf', 'afm'}, default: 'ttf'

The extension of the font file:

  • 'ttf': TrueType and OpenType fonts (.ttf, .ttc, .otf)

  • 'afm': Adobe Font Metrics (.afm)

directorystr, optional

If given, only search this directory and its subdirectories.

fallback_to_defaultbool

If True, will fall back to the default font family (usually"DejaVu Sans" or "Helvetica") if the first lookup hard-fails.

rebuild_if_missingbool

Whether to rebuild the font cache and search again if the firstmatch appears to point to a nonexisting font (i.e., the font cachecontains outdated entries).

Returns:
str

The filename of the best matching font.

Notes

This performs a nearest neighbor search. Each font is given asimilarity score to the target font properties. The first font withthe highest score is returned. If no matches below a certainthreshold are found, the default font (usually DejaVu Sans) isreturned.

The result is cached, so subsequent lookups don't have toperform the O(n) nearest neighbor search.

See theW3C Cascading Style Sheet, Level 1 documentationfor a description of the font finding algorithm.

staticget_default_size()[source]#

Return the default font size.

get_default_weight()[source]#

Return the default font weight.

get_font_names()[source]#

Return the list of available fonts.

score_family(families,family2)[source]#

Return a match score between the list of font families infamilies and the font family namefamily2.

An exact match at the head of the list returns 0.0.

A match further down the list will return between 0 and 1.

No match will return 1.0.

score_size(size1,size2)[source]#

Return a match score betweensize1 andsize2.

Ifsize2 (the size specified in the font file) is 'scalable', thisfunction always returns 0.0, since any font size can be generated.

Otherwise, the result is the absolute distance betweensize1 andsize2, normalized so that the usual range of font sizes (6pt -72pt) will lie between 0.0 and 1.0.

score_stretch(stretch1,stretch2)[source]#

Return a match score betweenstretch1 andstretch2.

The result is the absolute value of the difference between theCSS numeric values ofstretch1 andstretch2, normalizedbetween 0.0 and 1.0.

score_style(style1,style2)[source]#

Return a match score betweenstyle1 andstyle2.

An exact match returns 0.0.

A match between 'italic' and 'oblique' returns 0.1.

No match returns 1.0.

score_variant(variant1,variant2)[source]#

Return a match score betweenvariant1 andvariant2.

An exact match returns 0.0, otherwise 1.0.

score_weight(weight1,weight2)[source]#

Return a match score betweenweight1 andweight2.

The result is 0.0 if both weight1 and weight 2 are given as stringsand have the same value.

Otherwise, the result is the absolute value of the difference betweenthe CSS numeric values ofweight1 andweight2, normalized between0.05 and 1.0.

set_default_weight(weight)[source]#

Set the default font weight. The initial value is 'normal'.

classmatplotlib.font_manager.FontProperties(family=None,style=None,variant=None,weight=None,stretch=None,size=None,fname=None,math_fontfamily=None)[source]#

Bases:object

A class for storing and manipulating font properties.

The font properties are the six properties described in theW3C Cascading Style Sheet, Level 1 fontspecification andmath_fontfamily for math fonts:

  • family: A list of font names in decreasing order of priority.The items may include a generic font family name, either 'sans-serif','serif', 'cursive', 'fantasy', or 'monospace'. In that case, the actualfont to be used will be looked up from the associated rcParam during thesearch process infindfont. Default:rcParams["font.family"] (default:['sans-serif'])

  • style: Either 'normal', 'italic' or 'oblique'.Default:rcParams["font.style"] (default:'normal')

  • variant: Either 'normal' or 'small-caps'.Default:rcParams["font.variant"] (default:'normal')

  • stretch: A numeric value in the range 0-1000 or one of'ultra-condensed', 'extra-condensed', 'condensed','semi-condensed', 'normal', 'semi-expanded', 'expanded','extra-expanded' or 'ultra-expanded'. Default:rcParams["font.stretch"] (default:'normal')

  • weight: A numeric value in the range 0-1000 or one of'ultralight', 'light', 'normal', 'regular', 'book', 'medium','roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy','extra bold', 'black'. Default:rcParams["font.weight"] (default:'normal')

  • size: Either a relative value of 'xx-small', 'x-small','small', 'medium', 'large', 'x-large', 'xx-large' or anabsolute font size, e.g., 10. Default:rcParams["font.size"] (default:10.0)

  • math_fontfamily: The family of fonts used to render math text.Supported values are: 'dejavusans', 'dejavuserif', 'cm','stix', 'stixsans' and 'custom'. Default:rcParams["mathtext.fontset"] (default:'dejavusans')

Alternatively, a font may be specified using the absolute path to a fontfile, by using thefname kwarg. However, in this case, it is typicallysimpler to just pass the path (as apathlib.Path, not astr) to thefont kwarg of theText object.

The preferred usage of font sizes is to use the relative values,e.g., 'large', instead of absolute font sizes, e.g., 12. Thisapproach allows all text sizes to be made larger or smaller basedon the font manager's default font size.

This class accepts a single positional string asfontconfigpattern,or alternatively individual properties as keyword arguments:

FontProperties(pattern)FontProperties(*,family=None,style=None,variant=None,...)

This support does not depend on fontconfig; we are merely borrowing itspattern syntax for use here.

Note that Matplotlib's internal font manager and fontconfig use adifferent algorithm to lookup fonts, so the results of the same patternmay be different in Matplotlib than in other applications that usefontconfig.

copy()[source]#

Return a copy of self.

get_family()[source]#

Return a list of individual font family names or generic family names.

The font families or generic font families (which will be resolvedfrom their respective rcParams when searching for a matching font) inthe order of preference.

get_file()[source]#

Return the filename of the associated font.

get_fontconfig_pattern()[source]#

Get afontconfigpattern suitable for looking up the font asspecified with fontconfig'sfc-match utility.

This support does not depend on fontconfig; we are merely borrowing itspattern syntax for use here.

get_math_fontfamily()[source]#

Return the name of the font family used for math text.

The default font isrcParams["mathtext.fontset"] (default:'dejavusans').

get_name()[source]#

Return the name of the font that best matches the font properties.

get_size()[source]#

Return the font size.

get_size_in_points()[source]#

Return the font size.

get_slant()[source]#

Return the font style. Values are: 'normal', 'italic' or 'oblique'.

get_stretch()[source]#

Return the font stretch or width. Options are: 'ultra-condensed','extra-condensed', 'condensed', 'semi-condensed', 'normal','semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded'.

get_style()[source]#

Return the font style. Values are: 'normal', 'italic' or 'oblique'.

get_variant()[source]#

Return the font variant. Values are: 'normal' or 'small-caps'.

get_weight()[source]#

Set the font weight. Options are: A numeric value in therange 0-1000 or one of 'light', 'normal', 'regular', 'book','medium', 'roman', 'semibold', 'demibold', 'demi', 'bold','heavy', 'extra bold', 'black'

set_family(family)[source]#

Change the font family. Can be either an alias (generic nameis CSS parlance), such as: 'serif', 'sans-serif', 'cursive','fantasy', or 'monospace', a real font name or a list of realfont names. Real font names are not supported whenrcParams["text.usetex"] (default:False) isTrue. Default:rcParams["font.family"] (default:['sans-serif'])

set_file(file)[source]#

Set the filename of the fontfile to use. In this case, allother properties will be ignored.

set_fontconfig_pattern(pattern)[source]#

Set the properties by parsing afontconfigpattern.

This support does not depend on fontconfig; we are merely borrowing itspattern syntax for use here.

set_math_fontfamily(fontfamily)[source]#

Set the font family for text in math mode.

If not set explicitly,rcParams["mathtext.fontset"] (default:'dejavusans') will be used.

Parameters:
fontfamilystr

The name of the font family.

Available font families are defined in thedefault matplotlibrc file.

set_name(family)[source]#

Change the font family. Can be either an alias (generic nameis CSS parlance), such as: 'serif', 'sans-serif', 'cursive','fantasy', or 'monospace', a real font name or a list of realfont names. Real font names are not supported whenrcParams["text.usetex"] (default:False) isTrue. Default:rcParams["font.family"] (default:['sans-serif'])

set_size(size)[source]#

Set the font size.

Parameters:
sizefloat or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}, default:rcParams["font.size"] (default:10.0)

If a float, the font size in points. The string values denotesizes relative to the default font size.

set_slant(style)[source]#

Set the font style.

Parameters:
style{'normal', 'italic', 'oblique'}, default:rcParams["font.style"] (default:'normal')
set_stretch(stretch)[source]#

Set the font stretch or width.

Parameters:
stretchint or {'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded'}, default:rcParams["font.stretch"] (default:'normal')

If int, must be in the range 0-1000.

set_style(style)[source]#

Set the font style.

Parameters:
style{'normal', 'italic', 'oblique'}, default:rcParams["font.style"] (default:'normal')
set_variant(variant)[source]#

Set the font variant.

Parameters:
variant{'normal', 'small-caps'}, default:rcParams["font.variant"] (default:'normal')
set_weight(weight)[source]#

Set the font weight.

Parameters:
weightint or {'ultralight', 'light', 'normal', 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black'}, default:rcParams["font.weight"] (default:'normal')

If int, must be in the range 0-1000.

matplotlib.font_manager.afmFontProperty(fontpath,font)[source]#

Extract information from an AFM font file.

Parameters:
fontpathstr

The filename corresponding tofont.

fontAFM

The AFM font file from which information will be extracted.

Returns:
FontEntry

The extracted font properties.

matplotlib.font_manager.findSystemFonts(fontpaths=None,fontext='ttf')[source]#

Search for fonts in the specified font paths. If no paths aregiven, will use a standard set of system paths, as well as thelist of fonts tracked by fontconfig if fontconfig is installed andavailable. A list of TrueType fonts are returned by default withAFM fonts as an option.

matplotlib.font_manager.findfont(prop,fontext='ttf',directory=None,fallback_to_default=True,rebuild_if_missing=True)[source]#

Find the path to the font file most closely matching the given font properties.

Parameters:
propstr orFontProperties

The font properties to search for. This can be either aFontProperties object or a string defining afontconfig patterns.

fontext{'ttf', 'afm'}, default: 'ttf'

The extension of the font file:

  • 'ttf': TrueType and OpenType fonts (.ttf, .ttc, .otf)

  • 'afm': Adobe Font Metrics (.afm)

directorystr, optional

If given, only search this directory and its subdirectories.

fallback_to_defaultbool

If True, will fall back to the default font family (usually"DejaVu Sans" or "Helvetica") if the first lookup hard-fails.

rebuild_if_missingbool

Whether to rebuild the font cache and search again if the firstmatch appears to point to a nonexisting font (i.e., the font cachecontains outdated entries).

Returns:
str

The filename of the best matching font.

Notes

This performs a nearest neighbor search. Each font is given asimilarity score to the target font properties. The first font withthe highest score is returned. If no matches below a certainthreshold are found, the default font (usually DejaVu Sans) isreturned.

The result is cached, so subsequent lookups don't have toperform the O(n) nearest neighbor search.

See theW3C Cascading Style Sheet, Level 1 documentationfor a description of the font finding algorithm.

matplotlib.font_manager.get_font(font_filepaths,hinting_factor=None)[source]#

Get anft2font.FT2Font object given a list of file paths.

Parameters:
font_filepathsIterable[str, Path, bytes], str, Path, bytes

Relative or absolute paths to the font files to be used.

If a single string, bytes, orpathlib.Path, then it will be treatedas a list with that entry only.

If more than one filepath is passed, then the returned FT2Font objectwill fall back through the fonts, in the order given, to find a neededglyph.

Returns:
ft2font.FT2Font
matplotlib.font_manager.get_font_names()[source]#

Return the list of available fonts.

matplotlib.font_manager.get_fontext_synonyms(fontext)[source]#

Return a list of file extensions that are synonyms forthe given file extensionfileext.

matplotlib.font_manager.is_opentype_cff_font(filename)[source]#

Return whether the given font is a Postscript Compact Font Format Fontembedded in an OpenType wrapper. Used by the PostScript and PDF backendsthat cannot subset these fonts.

matplotlib.font_manager.json_dump(data,filename)[source]#

DumpFontManagerdata as JSON to the file namedfilename.

See also

json_load

Notes

File paths that are children of the Matplotlib data path (typically, fontsshipped with Matplotlib) are stored relative to that data path (to remainvalid across virtualenvs).

This function temporarily locks the output file to prevent multipleprocesses from overwriting one another's output.

matplotlib.font_manager.json_load(filename)[source]#

Load aFontManager from the JSON file namedfilename.

See also

json_dump
matplotlib.font_manager.list_fonts(directory,extensions)[source]#

Return a list of all fonts matching any of the extensions, foundrecursively under the directory.

matplotlib.font_manager.ttfFontProperty(font)[source]#

Extract information from a TrueType font file.

Parameters:
fontFT2Font

The TrueType font file from which information will be extracted.

Returns:
FontEntry

The extracted font properties.

matplotlib.font_manager.win32FontDirectory()[source]#

Return the user-specified font directory for Win32. This islooked up from the registry key

\\HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\ShellFolders\Fonts

If the key is not found,%WINDIR%\Fonts will be returned.

matplotlib.font_manager.fontManager[source]#

The global instance ofFontManager.

classmatplotlib.font_manager.FontEntry(fname='',name='',style='normal',variant='normal',weight='normal',stretch='normal',size='medium')[source]#

A class for storing Font properties.

It is used when populating the font lookup dictionary.

On this page