python - 如何将绘制的线保持在补丁下?

标签 python matplotlib

在下面的代码中,我画了一条线,然后在它上面画了一个不透明的补丁 (alpha=1)。我希望被补丁覆盖的那部分线被隐藏,但看起来好像这条线是在补丁之后绘制的。怎么改,让线不透?

plot heart

代码改编自this matplotlib example

import matplotlib.path as mpath
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt


fig, ax = plt.subplots()

Path = mpath.Path
path_data = [
    (Path.MOVETO, (1.58, -2.57)),
    (Path.CURVE4, (0.35, -1.1)),
    (Path.CURVE4, (-1.75, 2.0)),
    (Path.CURVE4, (0.375, 2.0)),
    (Path.LINETO, (0.85, 1.15)),
    (Path.CURVE4, (2.2, 3.2)),
    (Path.CURVE4, (3, 0.05)),
    (Path.CURVE4, (2.0, -0.5)),
    (Path.CLOSEPOLY, (1.58, -2.57)),
    ]
codes, verts = zip(*path_data)


path = mpath.Path(verts, codes)
# plot control points and connecting lines
x, y = zip(*path.vertices)
y2 = [_y-1 for _y in y]
line, = ax.plot(x, y2, 'go-')


patch = mpatches.PathPatch(path, facecolor='r', alpha=1)
ax.add_patch(patch)

ax.grid()
ax.axis('equal')
plt.show()

最佳答案

您可以指定补丁的 z 顺序(绿线有 zorder 2,所以大于 2 的都可以):

patch = mpatches.PathPatch(path, facecolor='r', alpha=1, zorder=5)

enter image description here

关于python - 如何将绘制的线保持在补丁下?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65381655/

相关文章:

python - Pandas:使用正则表达式清理包含单引号和括号的字符串列?

python - 使用 scipy、matplotlib 将数据拟合到多峰分布

python - Django 部署最佳实践

python - 将 pandas 数据帧的字符串列转换为 0 1 向量

python - 创建具有长名称的 .txt 文件时出现问题

绘制了 Python Matplotlib Slider 但不移动或更新

python - 在 x 轴上绘制日期

python - 如何从 matplotlib 中删除框架(pyplot.figure vs matplotlib.figure)(frameon=False 在 matplotlib 中有问题)

python - matplotlib 动画多个数据集

python - 在 python 的 sqlite3 模块中,使用 cursor.fetchone() 作为 while 循环的条件是否会获取一行?