簡體   English   中英

如何更改 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不是我系統上可用的 fonts 之一。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM