gpt4 book ai didi

python - 用 matplotlib 填充区域的补充

转载 作者:太空狗 更新时间:2023-10-29 21:51:03 24 4
gpt4 key购买 nike

我目前正在使用 Python 和 matplotlib 实现一些东西。我知道如何绘制多边形以及如何填充多边形,但如何填充多边形内部的所有内容?为了更清楚,我想修改下面的结果,通过剪切水平和垂直的红线以获得一个红色矩形(外面的一切都像现在一样被孵化): enter image description here

最佳答案

This post问(和回答)本质上是这个问题。查看接受的答案中的“编辑 2”。它描述了如何创建一个矢量多边形,其大小与绘图边界的大小相同,然后如何在其中创建一个孔以匹配您想要补充的形状。它通过分配定义笔在移动时是否绘制的行代码来实现这一点。

这是与此问题相关的上述帖子的部分:

import numpy as np
import matplotlib.pyplot as plt

def main():
# Contour some regular (fake) data
grid = np.arange(100).reshape((10,10))
plt.contourf(grid)

# Verticies of the clipping polygon in counter-clockwise order
# (A triange, in this case)
poly_verts = [(2, 2), (5, 2.5), (6, 8), (2, 2)]

mask_outside_polygon(poly_verts)

plt.show()

def mask_outside_polygon(poly_verts, ax=None):
"""
Plots a mask on the specified axis ("ax", defaults to plt.gca()) such that
all areas outside of the polygon specified by "poly_verts" are masked.

"poly_verts" must be a list of tuples of the verticies in the polygon in
counter-clockwise order.

Returns the matplotlib.patches.PathPatch instance plotted on the figure.
"""
import matplotlib.patches as mpatches
import matplotlib.path as mpath

if ax is None:
ax = plt.gca()

# Get current plot limits
xlim = ax.get_xlim()
ylim = ax.get_ylim()

# Verticies of the plot boundaries in clockwise order
bound_verts = [(xlim[0], ylim[0]), (xlim[0], ylim[1]),
(xlim[1], ylim[1]), (xlim[1], ylim[0]),
(xlim[0], ylim[0])]

# A series of codes (1 and 2) to tell matplotlib whether to draw a line or
# move the "pen" (So that there's no connecting line)
bound_codes = [mpath.Path.MOVETO] + (len(bound_verts) - 1) * [mpath.Path.LINETO]
poly_codes = [mpath.Path.MOVETO] + (len(poly_verts) - 1) * [mpath.Path.LINETO]

# Plot the masking patch
path = mpath.Path(bound_verts + poly_verts, bound_codes + poly_codes)
patch = mpatches.PathPatch(path, facecolor='white', edgecolor='none')
patch = ax.add_patch(patch)

# Reset the plot limits to their original extents
ax.set_xlim(xlim)
ax.set_ylim(ylim)

return patch

if __name__ == '__main__':
main()

关于python - 用 matplotlib 填充区域的补充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4814318/

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