gpt4 book ai didi

python - 如何在 matplotlib 中很好地绘制裁剪的分层艺术家?

转载 作者:太空宇宙 更新时间:2023-11-04 03:24:10 27 4
gpt4 key购买 nike

假设您在 matplotlib 绘图中有三位艺术家。在保留整个区域可见的低级别艺术家的同时,不在顶级艺术家的 bbox 中显示中级艺术家的最简单方法是什么?

说明我想要实现的目标:

Illustration of layered clipping

如果不需要能够看到最低层,顶层图的非透明面色就足够了。这不适用于三个级别,因为两个较低级别都将被隐藏。

参见 this IPython notebook for a solution using shapely .这是一个尚未完全发挥作用的纯 matplotlib 示例,但我希望有一种更简单的方法来获得我尚未想到的相同结果。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import patches, cm
from matplotlib.path import Path
fig, ax = plt.subplots()
imdata = np.random.randn(10, 10)
ax.imshow(imdata, extent=(0, 1, 0, 1), aspect='auto', cmap=cm.coolwarm)
text = ax.text(0.5, 0.5, 'Text', fontsize='xx-large', fontweight='bold',
color='k', ha='center', va='center')
renderer = fig.canvas.get_renderer()
bbox = text.get_window_extent(renderer).transformed(ax.transData.inverted())
bboxrect = patches.Rectangle((bbox.x0, bbox.y0), bbox.width, bbox.height)
bbpath = bboxrect.get_path().transformed(bboxrect.get_patch_transform())
patch = patches.Rectangle((0.3, 0.3), 0.4, 0.4)
path = patch.get_path().transformed(patch.get_patch_transform())
path = Path.make_compound_path(path, bbpath)
patch = patches.PathPatch(path, facecolor='none', hatch=r'//')
ax.add_patch(patch)

最佳答案

我想出了另一个更简洁的答案:它涉及为其中有一个孔的阴影区域创建一个剪切蒙版,以便您可以看到它后面的背景中的一切

from matplotlib.path import Path
from matplotlib.patches import PathPatch

def DoubleRect(xy1, width1, height1,
xy2, width2, height2, **kwargs):
base = np.array([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)])
verts = np.vstack([xy1 + (width1, height1) * base,
xy2 + (width2, height2) * base[::-1],
xy1])
codes = 2 * ([Path.MOVETO] + 4 * [Path.LINETO]) + [Path.CLOSEPOLY]
return PathPatch(Path(verts, codes), **kwargs)

fig, ax = plt.subplots()
imdata = np.random.randn(10, 10)

# plot the image
im = ax.imshow(imdata, extent=(0, 1, 0, 1), aspect='auto',
cmap='coolwarm', interpolation='nearest')

# plot the hatched rectangle
patch = plt.Rectangle((0.3, 0.3), 0.4, 0.4, facecolor='none',
hatch=r'//')
ax.add_patch(patch)

# add the text
text = ax.text(0.5, 0.5, 'Text', fontsize='xx-large', fontweight='bold',
color='k', ha='center', va='center')

# create a mask for the hatched rectangle
mask = DoubleRect((0, 0), 1, 1, (0.4, 0.45), 0.2, 0.1,
facecolor='none', edgecolor='black')
ax.add_patch(mask)
patch.set_clip_path(mask)

enter image description here

关于python - 如何在 matplotlib 中很好地绘制裁剪的分层艺术家?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33622485/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com