Styling part of label in legend in matplotlib

Question:

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

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


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

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


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',
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}$",

Categories: questions
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.