如何使用 Matplotlib 在圖表中放置自定義圖例符號?


要在一個圖表中繪製自定義圖例符號,我們可以採取以下步驟 −

  • 設定圖的大小並調整子圖之間和周圍的填充。
  • 繼承HandlerPatch 類,重寫建立藝術家的方法,在圖表中新增一個橢圓形貼片,並返回貼片處理程式。
  • 使用Circle 類在圖表上繪製一個圓。
  • 在當前軸上新增一個圓貼片。
  • 使用legend() 方法將圖例放置在圖表上。
  • 使用show() 方法顯示圖形。

示例

import matplotlib.pyplot as plt, matplotlib.patches as mpatches
from matplotlib.legend_handler import HandlerPatch

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

class HandlerEllipse(HandlerPatch):
   def create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans):
      center = 0.5 * width - 0.5 * xdescent, 0.5 * height - 0.5 * ydescent
      p = mpatches.Ellipse(xy=center, width=width + xdescent, height=height + ydescent)
      self.update_prop(p, orig_handle, legend)
      p.set_transform(trans)
      return [p]

c = mpatches.Circle((0.5, 0.5), 0.25, facecolor="green", edgecolor="red", linewidth=1)
plt.gca().add_patch(c)

plt.legend([c], ["An ellipse,Customized legend element"],
handler_map={mpatches.Circle: HandlerEllipse()})

plt.show()

輸出

更新於: 2021 年 6 月 5 日

812 次瀏覽

開啟你的 職業生涯

透過完成該課程獲得認證

開始
廣告
© . All rights reserved.