使用matplotlib填充区域的补充

时间:2011-01-27 08:54:37

标签: python matplotlib

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

2 个答案:

答案 0 :(得分:4)

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()

答案 1 :(得分:1)

如果您只需要矩形的补码,则可以在其周围绘制4个矩形(就像示例图像中可见的4个矩形)。可以使用xlim()ylim()获取绘图边的坐标。

我不确定Matplotlib是否提供了绘制多边形外部的方法......