如何在 Matplotlib 中使用自定義陰影填充多邊形?


若要在 matplotlib 中使用自定義陰影填充多邊形,我們可以覆蓋 matplotlib.hatch.Shapes 類。

步驟

  • 設定影像尺寸並調整子圖之間和周圍的填充。
  • 使用 polygon 類建立陰影形狀並獲取路徑。
  • 覆蓋具有 shape_vertices, shape_codes, 等形狀的自定義陰影形狀類。
  • 建立新影像或啟用現有影像。
  • 將一個軸新增到影像,作為子圖排列的一部分。
  • 新增形狀為 polygon 的軸補丁。
  • 設定陰影圖案。
  • 要顯示影像,請使用 show() 方法。

示例

import matplotlib.hatch
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon

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

my_hatch_shape = Polygon(
   [[0., 0.4], [-0.3, 0.1], [0.1, 0.2]],
   closed=True, fill=False).get_path()

class MyCustomHatch(matplotlib.hatch.Shapes):
   filled = True
   size = 1.0
   path = my_hatch_shape

   def __init__(self, hatch, density):
      self.num_rows = (hatch.count('c')) * density
      self.shape_vertices = self.path.vertices
      self.shape_codes = self.path.codes
      matplotlib.hatch.Shapes.__init__(self, hatch, density)

matplotlib.hatch._hatch_types.append(MyCustomHatch)

fig = plt.figure()
ax = fig.add_subplot(111)

pg = ax.add_patch(Polygon(
   [[0.2, 0.2], [0.2, 0.8], [0.8, 0.1]],
   closed=True, fill=False))

pg.set_hatch('c')

plt.show()

輸出

更新於: 07-7-2021

902 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始使用
廣告
© . All rights reserved.