str2tex

Convert strings to LaTeX strings in math environment used by matplotlib’s usetex

This module was written by Matthias Cuntz while at Department of Computational Hydrosystems, Helmholtz Centre for Environmental Research - UFZ, Leipzig, Germany, and continued while at Institut National de Recherche pour l’Agriculture, l’Alimentation et l’Environnement (INRAE), Nancy, France.

copyright:

Copyright 2015-2022 Matthias Cuntz, see AUTHORS.rst for details.

license:

MIT License, see LICENSE for details.

The following functions are provided:

str2tex(strin[, space2linebreak, bold, ...])

Convert strings to LaTeX strings in math environment used by matplotlib's usetex

History
  • Written Oct 2015 by Matthias Cuntz (mc (at) macu (dot) de)

  • Use raw strings for escaped characters, Nov 2021, Matthias Cuntz

  • Bug in space2linebreak in complex strings with spaces; do space2linebreak first, Nov 2021, Matthias Cuntz

  • Bug in escaping %, Nov 2021, Matthias Cuntz

  • Remove trailing $mathrm{}$, Nov 2021, Matthias Cuntz

  • Ported into pyjams, Nov 2021, Matthias Cuntz

  • Better handling of linebreaks in Matplotlib and LaTeX mode, Nov 2021, Matthias Cuntz

  • More consistent docstrings, Jan 2022, Matthias Cuntz

  • Use input2array, array2input, Jun 2022, Matthias Cuntz

  • Do not escape % if not usetex, Apr 2023, Matthias Cuntz

  • Add unicode symbol degree °, which get replaced by ^circ if usetex==True, Apr 2023, Matthias Cuntz

str2tex(strin, space2linebreak=False, bold=False, italic=False, usetex=False)[source]

Convert strings to LaTeX strings in math environment used by matplotlib’s usetex

Strings are embedded into ‘$mathrm{strin}$’ by default but can be embedded into ‘mathbf’ and ‘mathit’. Spaces are escaped but can be replaced by linebreaks.

Parameters:
  • strin (str or array-like of str) – string (array)

  • space2linebreak (bool, optional) – Replace space (’ ‘) by linebreak (’n’) if True (default: False)

  • bold (bool, optional) – Use ‘mathbf’ instead of ‘mathrm’ if True (default: False)

  • italic (bool, optional) – Use ‘mathit’ instead of ‘mathrm’ if True (default: False)

  • usetex (bool, optional) – Treat only linebreaks and comments if False (default)

Returns:

string – string (array) that can be used in matplotlib independent of usetex.

Return type:

str

Examples

fig = plt.figure()
tit = str2tex('A $S_{Ti}$ is great\nbut use-less', usetex=usetex)
fig.suptitle(tit)