pythonmatplotliblegendlegend-properties

How to change the font family of matplotlib legend AND legend title?


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.


Solution

  • A couple points:

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