1

I would like to use the font family "Consolas" in my matplotlib legend in order to benefit the monospaced font. I also want a legend title.

But it seems that when I change the font family of my legend, it erase the legend title.

Here is a code to see the problem:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
plt.plot(np.linspace(0, 10), np.linspace(0, 1), label='First plot     #1')
plt.plot(np.linspace(0, 10), np.linspace(0, 2), label='Second plot    #2')
plt.legend(loc='best', title="My Awesome Legend Title")

enter image description here

# I would like to use a Monospaced font so I have found this snippet to do so
plt.setp(ax.legend().texts, family='Consolas')
# But as you can see, my legend title just disapeared !!!

enter image description here

# how can I do ?
# Can I force again the legend title ?
ax.legend(title="My NEW Awesome Legend Title")
# Yes ! But it changes the font family again to default.

enter image description here

Do you have any solution ? Thanks for your help and precious time.

Samovian
  • 173
  • 1
  • 7
  • Does this answer your question? [How to change fonts in matplotlib (python)?](https://stackoverflow.com/questions/21321670/how-to-change-fonts-in-matplotlib-python) Spefically use rcParams to set the global font as per the second answer – Chris Mar 01 '22 at 13:58
  • I haven't succeed yet using rcParams but my matplotlib and python knowledge is limited. I also use many figures in my codes and want the "Consolas" font family only on few of legend and not everywhere (xlabel etc.) – Samovian Mar 01 '22 at 14:13
  • [You can change rcParams temporarily](https://matplotlib.org/stable/tutorials/introductory/customizing.html#temporary-rc-settings). – Mr. T Mar 01 '22 at 16:20

1 Answers1

3

A couple points:

  • The title of the legend disappears as soon as I execute ax.legend(), so the disappearance is not actually caused by setting the font. This simply creates a new legend, with no title.
  • The legend title and legend texts are separate items.

This worked for me:

leg = ax.get_legend()
plt.setp(leg.get_title(), family='Ubuntu Mono')
plt.setp(leg.get_texts(), family='Ubuntu Mono')

(Consolas is not one of the fonts available on my system.)

Warren Weckesser
  • 110,654
  • 19
  • 194
  • 214
  • Works perfectly for me too. It solves the problem efficiently and explains why. Thanks for sharing your experience. It is greatly appreciated. – Samovian Mar 02 '22 at 08:13