59

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

kmario23
  • 57,311
  • 13
  • 161
  • 150
englebip
  • 955
  • 1
  • 11
  • 17

3 Answers3

53

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()
  • 12
    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`. – ImportanceOfBeingErnest May 22 '17 at 23:37
  • 2
    @homayoun the \it works fine, but the \bf does not. I sthere a link to the documentation where? what other \handles are there? – dmeu Jun 07 '17 at 07:20
  • Here is some documentation for the `$...$` syntax: https://matplotlib.org/users/mathtext.html –  Jun 27 '17 at 07:44
  • 11
    @dmeu for bold it should be \\bf (double slashes) – Claudiu Creanga Oct 27 '17 at 12:57
  • 5
    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. – Åsmund Mar 19 '18 at 12:50
  • 1
    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 – ignoring_gravity Sep 11 '18 at 16:25
  • 7
    use `\ ` (backslash space) to insert a space in mathmode. $these\ are\ words$. `$\mathrm{whatever}$` is also useful to know about. – travc Apr 09 '19 at 05:12
  • 1
    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}$")`. – Aerinmund Fagelson Apr 21 '22 at 10:27
43

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

Community
  • 1
  • 1
joris
  • 133,120
  • 36
  • 247
  • 202
  • 1
    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. – englebip Dec 05 '11 at 14:11
  • 2
    On Ubuntu 12.04, I needed `texlive`, `texlive-latex-extra`, and `dvipng` to get this example working. – Ulrich Stern Apr 18 '16 at 14:00
  • 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`** – kmario23 May 30 '20 at 21:20
  • I can't get a text to in sans serif font (such as Helvetica) with italics. I have tried used `\mathregular` but nothing changes. – s.ouchene Sep 03 '22 at 07:31
5

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}$",
kmario23
  • 57,311
  • 13
  • 161
  • 150