Skip to main content
 首页 » 编程设计

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

2024年10月24日10qq78292959

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

说明我想要实现的目标:

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

参见 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)