如何在 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()輸出

廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP