2011-01-27 98 views
7

我目前正在用Python和matplotlib實現一些東西。我知道如何繪製多邊形以及如何填充它們,但是如何填充的所有內容(除外)?爲了更清楚一點,我想修改下面的結果,使用axhspanaxvspan獲得的結果,通過剪切水平和垂直紅線以獲得一個紅色的矩形(外面的一切都是現在的陰影) : enter image description here用matplotlib填補區域的補充

回答

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

你指的文章是關於掩蔽2D像素圖像。儘管這可能是問題的近似解決方案,但理想的解決方案是通過矢量繪圖(而不是像素繪圖)。 – EOL 2011-01-27 21:58:52

1

如果您只需要矩形的補充,您可以改爲在其周圍繪製4個矩形(如您的示例圖像中可見的4個矩形)。繪圖邊緣的座標可以通過xlim()ylim()獲得。

我不知道,Matplotlib提供畫多邊形外的一種方式......