Python 用matplotlib填充区域补码
我目前正在用Python和matplotlib实现一些东西。我知道如何绘制多边形,也知道如何填充它们,但是除了多边形的内部,我如何填充所有东西?为了更清楚,我想修改下面的结果,使用Python 用matplotlib填充区域补码,python,matplotlib,Python,Matplotlib,我目前正在用Python和matplotlib实现一些东西。我知道如何绘制多边形,也知道如何填充它们,但是除了多边形的内部,我如何填充所有东西?为了更清楚,我想修改下面的结果,使用axhspan和axvspan,通过剪切水平和垂直红线来获得一个红色矩形(在该矩形外,所有内容都是现在的图案填充): 如果您只需要一个矩形的补码,可以在其周围绘制4个矩形(如示例图像中可见的4个矩形)。可以使用xlim()和ylim()获得打印边的坐标 我不确定Matplotlib是否提供了一种绘制多边形外部的方法…问
axhspan
和axvspan
,通过剪切水平和垂直红线来获得一个红色矩形(在该矩形外,所有内容都是现在的图案填充):
如果您只需要一个矩形的补码,可以在其周围绘制4个矩形(如示例图像中可见的4个矩形)。可以使用
xlim()
和ylim()
获得打印边的坐标
我不确定Matplotlib是否提供了一种绘制多边形外部的方法…问(并回答)了这个问题。查看已接受答案中的“编辑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()
你提到的帖子是关于屏蔽2D像素图像的。尽管这可能是问题的近似解决方案,但理想的解决方案是通过矢量绘制(而不是像素绘制)。向下滚动到已接受答案的“Edid 2”,您将找到矢量解决方案。谢谢!实际上,“编辑2”中的
mask\u outside\u polygon
函数与一些阴影一起实现了这一点。