Styling part of label in legend in matplotlib


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

Asked By: englebip



As silvado mentions in his comment, you can use LaTeX rendering for more flexible control of the text rendering. See here for more information:

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}")

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).

Answered By: joris

Write between $$ to force matplotlib to interpret it.

import matplotlib.pyplot as plt

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

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:

          loc='upper right',
          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}$",
Answered By: kmario23