如何在 Matplotlib 中為圖例行新增標題?


要為 Matplotlib 中的圖例行新增標題,我們可以採取以下步驟 -

  • 設定圖形大小並調整子圖之間及其周圍的邊距。

  • 使用 numpy 建立**y**資料點。

  • 列出**標記**和**標籤**。

  • 建立一個圖形和一組子圖。

  • 使用**plot()**方法繪製線條,並使用不同的標籤和標記。

  • 獲取一半圖的繪圖控制代碼。

  • 獲取圖例的標籤。

  • 將圖例放置在繪圖上。

  • 為了顯示圖形,使用**show()**方法。

示例

import matplotlib.pyplot as plt
import numpy as np

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

y = np.exp(-np.arange(5))

markers = ["s", "o", "*"]
labels = ["one", "two"]

fig, ax = plt.subplots()

for i in range(6):
   ax.plot(y * i + i / 2., marker=markers[i // 2], label=labels[i % 2])
h, l = ax.get_legend_handles_labels()
ph = [plt.plot([], marker="", ls="")[0]] * 2
handles = ph + h

labels = ["Title 1:", "Title 2:"] + l
plt.legend(handles, labels, ncol=4)

plt.show()

輸出

更新於: 10-8-2021

2K+ 瀏覽

開啟你的 職業生涯

透過完成課程取得認證

開始
廣告