Matplotlibの複合パスに穴を開けるには?

Matplotlibの複合パスに穴を開けるには?

複合PathPatchの内側境界を逆向きにすると穴になります。4×4の外側から2×2を引く面積は12です。

この記事の内容

公開・実測日:2026年11月22日。

どのコードを変えるとこの結果になりますか?

複合PathPatchの内側境界を逆向きにすると穴になります。4×4の外側から2×2を引く面積は12です。 作例の数値は data.csv の boundary, x, y 列で確認できます。

本記事では説明用のシミュレーションデータを使います。

元の出力: 比較図のタイトルは「Same winding fills the inner square」です。図中の軸と条件を保って結果と比較します。
元のサイズで図を開く
元の出力. 比較図のタイトルは「Same winding fills the inner square」です。図中の軸と条件を保って結果と比較します。
結果の出力: 複合PathPatchの内側境界を逆向きにすると穴になります。4×4の外側から2×2を引く面積は12です。
元のサイズで図を開く
結果の出力. 複合PathPatchの内側境界を逆向きにすると穴になります。4×4の外側から2×2を引く面積は12です。

実際の出力はどう変わりますか?

外側の正方形を一周し、内側は逆向きにたどります。外側の面積16から穴の4を引くと、塗られる面積は12です。

boundaryxy
outer0.00.0
outer4.00.0
outer4.04.0
outer0.04.0
outer0.00.0
inner1.01.0
inner3.01.0
inner3.03.0
inner1.03.0
inner1.01.0

表は入力の全行です。 (10)

この設定を使う前に何を確認しますか?

両方の境界を閉じ、向きによって非ゼロ巻き数の塗りを制御します。元のデータは保持します。

図を再現してファイルを取得するには?

書き込み可能なフォルダーで python example.py を実行します。実行環境は Python 3.12.4、Matplotlib 3.8.4、NumPy 1.26.4です。スクリプトと同じ場所に data.csv、before.png、after.png、after.pdf を作ります。

以下は本文で使ったコード、データ、実行結果のファイルです。コードを動かしたり、自分の結果と見比べたりするときに使ってください。

  • example.py自分のパソコンで実行できる例のコード一式です。
  • data.csv例に使った入力データです。表として開けます。
  • before.png比較用の変更前の図です。
  • after.png本文の設定で作成した結果の図です。
  • after.pdf閲覧やページへの配置に使える PDF 形式の結果です。
  • 利用条件 · LICENSE.txtコード・データ・図の利用条件と、出典・フォントの情報。
ファイルの確認
  • hashes.jsonダウンロードしたファイルの完全性を確認するための照合値です。

完全な Python コード

# Original Bopbun example code and synthetic input: CC0-1.0.
# Python 3.12.4, NumPy 1.26.4, Matplotlib 3.8.4. See LICENSE.txt for font rights.
from pathlib import Path
import csv,json,math,itertools
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib import colors,patches
OUT=Path(__file__).resolve().parent
plt.rcdefaults()
plt.rcParams.update({'font.family':'DejaVu Sans','font.size':11,'figure.dpi':120,'savefig.dpi':160,'pdf.fonttype':42})
def pair():
    f0,a0=plt.subplots(figsize=(7.2,4.5),layout='constrained')
    f1,a1=plt.subplots(figsize=(7.2,4.5),layout='constrained')
    return f0,a0,f1,a1
def data_file(names,rows):
    with (OUT/'data.csv').open('w',newline='',encoding='utf-8') as f:
        w=csv.writer(f);w.writerow(names);w.writerows(rows)
before,a0,after,ax=pair()
from matplotlib.path import Path as PlotPath
outer=np.array([[0.,0],[4,0],[4,4],[0,4],[0,0]]);inner=np.array([[1.,1],[3,1],[3,3],[1,3],[1,1]]);codes=[PlotPath.MOVETO]+[PlotPath.LINETO]*3+[PlotPath.CLOSEPOLY]
for aa,ring,title in [(a0,inner,'Same winding fills the inner square'),(ax,inner[::-1],'Opposite winding leaves a hole')]:
    path=PlotPath.make_compound_path(PlotPath(outer,codes),PlotPath(ring,codes));aa.add_patch(patches.PathPatch(path,facecolor='#75a9cf'));aa.set(xlim=(-.3,4.3),ylim=(-.3,4.3),aspect='equal',xlabel='x',ylabel='y',title=title)
data_file(['boundary','x','y'],[('outer',*p) for p in outer]+[('inner',*p) for p in inner]);metric=(outer[:,0].max()-outer[:,0].min())*(outer[:,1].max()-outer[:,1].min())-(inner[:,0].max()-inner[:,0].min())*(inner[:,1].max()-inner[:,1].min())

before.savefig(OUT/'before.png')
after.savefig(OUT/'after.png')
after.savefig(OUT/'after.pdf',metadata={'CreationDate':None,'ModDate':None})
after.canvas.draw()
print(json.dumps({'metric':float(metric),'axes':len(after.axes),'inputRows':sum(1 for _ in (OUT/'data.csv').open())-1}))
plt.close('all')

参照元と商用利用の条件は何ですか?

独自のコードとデータは CC0-1.0です。図は DejaVu Sans を使い、フォントの許諾は別途保持します。Matplotlib と NumPy はインストール済みの依存関係を呼び出し、配布しません。

関連する別の質問はどの解答で確認できますか?

研究図表の質問一覧