Styling part of label in legend in matplotlib

PythonMatplotlibTextCustomizationLegend

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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 2 - Python

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 3 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionenglebipView Question on Stackoverflow
Solution 1 - PythonHomayoun HamedmoghadamView Answer on Stackoverflow
Solution 2 - PythonjorisView Answer on Stackoverflow
Solution 3 - Pythonkmario23View Answer on Stackoverflow