如何更改 matplotlib 图例和图例标题的字体系列?

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

我想在我的 matplotlib 图例中使用字体系列“Consolas”,以使等宽字体受益。我也想要传奇称号

但似乎当我更改图例的字体系列时,它会删除图例标题。

这里有代码可以看出问题:

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

# 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 !!!

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

你有什么解决办法吗? 感谢您的帮助和宝贵的时间。

几点:

  • 我一执行ax.legend()图例的标题就消失了,所以消失其实不是设置字体造成的。这只是创建了一个没有标题的新图例。
  • 图例标题和图例文本是单独的项目。

这对我有用:

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

Consolas 不是我系统上可用的字体之一。)