Styling part of label in legend in matplotlib

49,039

Solution 1

As silvado mentions in his comment, you can use LaTeX rendering for more flexible control of the text rendering. See here for more information: http://matplotlib.org/users/usetex.html

An example:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc

# activate latex text rendering
rc('text', usetex=True)

x = np.arange(10)
y = np.random.random(10)
z = np.random.random(10)

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y, label = r"This is \textbf{line 1}")
ax.plot(x, z, label = r"This is \textit{line 2}")
ax.legend()
plt.show()

enter image description here

Note the 'r' before the strings of the labels. Because of this the \ will be treated as a latex command and not interpreted as python would do (so you can type \textbf instead of \\textbf).

Solution 2

Write between $$ to force matplotlib to interpret it.

import matplotlib.pyplot as plt

plt.plot(range(10), range(10), label = "Normal text $\it{Italics}$")
plt.legend()
plt.show()

Solution 3

Adding more options to the above answer by fixing the issues with that answer, with OO interface not just the state-based pyplot interface, possibility to have spaces as part of the text, boldface option in addition to italics:

ax.legend(handles=legend_handles,
          labels=legend_labels,
          loc='upper right',
          shadow=True,
          fancybox=True,
          facecolor='#C19A6B',
          title="$\\bf{BOLDFACED\ TITLE}$",     # to boldface title with space in between
          prop={'size': 12, 'style': 'italic'}  # properties for legend text
         )

For italicized title with space in between replace the above title with,

 title="$\\it{ITALICIZED\ TITLE}$",
Share:
49,039

Related videos on Youtube

englebip
Author by

englebip

Updated on July 09, 2022

Comments

  • englebip
    englebip almost 2 years

    Is it possible to have part of the text of a legend in a particular style, let's say, bold or italic?

    • silvado
      silvado over 12 years
      Have you tried whether tex-formatting works for the legend?
  • englebip
    englebip over 12 years
    Thanks, this is exactly what I was looking for! In case it helps someone else, I had trouble to run the example code in Ubuntu 11.10 until I installed the texlive (I had texlive-base) and texlive-latex-extra packages.
  • Ulrich Stern
    Ulrich Stern about 8 years
    On Ubuntu 12.04, I needed texlive, texlive-latex-extra, and dvipng to get this example working.
  • ImportanceOfBeingErnest
    ImportanceOfBeingErnest about 7 years
    This is indeed much easier than the accepted answer and does not require latex to be installed. For bold text use \bf instead of \it.
  • dmeu
    dmeu almost 7 years
    @homayoun the \it works fine, but the \bf does not. I sthere a link to the documentation where? what other \handles are there?
  • Admin
    Admin almost 7 years
    Here is some documentation for the $...$ syntax: matplotlib.org/users/mathtext.html
  • Claudiu Creanga
    Claudiu Creanga over 6 years
    @dmeu for bold it should be \\bf (double slashes)
  • Åsmund
    Åsmund about 6 years
    Doesn't work for sentences: Spaces between words disappear, since this feature is meant for math, not text. You'll have to bold/italic each word separately.
  • ignoring_gravity
    ignoring_gravity over 5 years
    You can do something like this to retain the spaces: 'Normal text' + ' '.join(['$\it{'+i+'}$' for i in my_label.split(' ')]), where my_label is the label you want to make italic
  • travc
    travc about 5 years
    use \ (backslash space) to insert a space in mathmode. $these\ are\ words$. $\mathrm{whatever}$ is also useful to know about.
  • kmario23
    kmario23 almost 4 years
    On the latest version of Ubuntu 19.10 one would also need cm-super; So the whole list of packages now needed is gonna be the following, in a single installation command: sudo apt-get install dvipng texlive-latex-extra texlive-fonts-recommended cm-super
  • Aerinmund Fagelson
    Aerinmund Fagelson about 2 years
    Nice answer, though I was applying this in to the title keyword in a matplotlib legend and I had to use an r-string to get it to work, i.e. plt.legend(title=r"Normal text $\it{Italics}$").