您可以使用路徑來構造矩形。爲了定位矩形,路徑的頂點可以被轉換和轉換。然後,使用倒轉頂點從路徑中切出的事實,在外部矩形中創建一個孔。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.path import Path
from matplotlib.patches import PathPatch, Rectangle
fig, ax = plt.subplots()
imdata = np.random.randn(10, 10)
# create rectangle, coordinates are ignored
rec = Rectangle((0,0),1,1).get_path()
#the big rectangle
r0 = rec.vertices+0.5
# r1 and r2 are the rectangles to cut out of r0
r1 = 0.6+rec.vertices[::-1]*0.35
r2 = 1+rec.vertices[::-1]*0.35
path = Path(vertices=np.concatenate([r0, r1, r2]),
codes=np.concatenate([rec.codes]*3))
im = ax.imshow(imdata, extent=(0, 2, 0, 2), aspect='equal',
cmap='coolwarm', interpolation='nearest')
patch = PathPatch(path, facecolor='w')
ax.add_patch(patch)
plt.tight_layout()
plt.show()
或者,溶液,其可以更容易地指定矩形的座標:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.path import Path
from matplotlib.patches import PathPatch, Rectangle
fig, ax = plt.subplots()
imdata = np.random.randn(10, 10)
def create_rec(x0, y0, width, height):
rec_patch = Rectangle((x0, y0),width, height)
rec_path = rec_patch.get_path()
rec_path = rec_patch.get_patch_transform().transform_path(rec_path)
return rec_path.vertices, rec_path.codes
#the big rectangle
r0,c = create_rec(0.3, 0.6, 1, 1.2)
# r1 and r2 are the rectangles to cut out of r0
r1,c = create_rec(0.4, 0.7, 0.3, 0.4)
r2,c = create_rec(0.8, 1, 0.4, 0.5)
path = Path(vertices=np.concatenate([r0, r1[::-1], r2[::-1]]),
codes=np.concatenate([c]*3))
im = ax.imshow(imdata, extent=(0, 2, 0, 2), aspect='equal',
cmap='coolwarm', interpolation='nearest')
patch = PathPatch(path, facecolor='w')
ax.add_patch(patch)
plt.tight_layout()
plt.show()
爲了解釋的情況下的矩形部分是外原始的矩形,以下(基於第二種解決方案)可能會有所幫助:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.path import Path
from matplotlib.patches import PathPatch, Rectangle
fig, ax = plt.subplots()
imdata = np.random.randn(10, 10)
def create_rec(x0, y0, width, height):
rec_patch = Rectangle((x0, y0),width, height)
rec_path = rec_patch.get_path()
rec_path = rec_patch.get_patch_transform().transform_path(rec_path)
return rec_path.vertices, rec_path.codes
#the big rectangle
r0,c = create_rec(0.3, 0.6, 1, 1.2)
# r1 and r2 are the rectangles to cut out of r0
r1,c = create_rec(0.2, 0.5, 0.3, 0.4)
r2,c = create_rec(0.8, 1, 0.4, 0.5)
path = Path(vertices=np.concatenate([r0, r1[::-1], r2[::-1]]),
codes=np.concatenate([c]*3))
im = ax.imshow(imdata, extent=(0, 2, 0, 2), aspect='equal',
cmap='coolwarm', interpolation='nearest')
patho = Path(vertices=r0,codes=c)
patcho = PathPatch(patho, facecolor='none', edgecolor="none")
ax.add_patch(patcho)
patch = PathPatch(path, facecolor='w', clip_path=patcho, edgecolor="none")
ax.add_patch(patch)
plt.show()
感謝您的時間。不幸的是,這只是事實的一半。如果將第一個示例更改爲'r1 = 0.2 + rec.vertices [:: - 1] * 0.35',您會發現它不是剪切,而是反轉。任何想法如何解決這個問題? –
嗯,我回答了你的問題,它的內容是*「我想從之前添加的矩形中切出其他幾個矩形」*。如果你想要別的東西,隨意編輯這個問題。 – ImportanceOfBeingErnest
我認爲,我的問題並沒有真正的誤導。不過,我會在那裏強調一下。再次感謝。附:完成。 –