2011-01-27 20 views
7

現在、Pythonとmatplotlibで何かを実装しています。ポリゴンの描画方法と塗り方を知っていますが、どのように塗りつぶすのですか以外はポリゴンの内部?より明確にするために、axhspanaxvspanのを使用して得られた結果を、水平と垂直の赤い線をクリッピングして赤い四角形を得て、下の結果を修正したいと思います。 : enter image description herematplotlibの領域の補完

答えて

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

+0

受け入れられた答えの「Edid 2」までスクロールダウンすると、ベクトル解が見つかります。 – Paul

+0

ありがとうbpowah!実際、 'Edit 2'の 'mask_outside_polygon'関数といくつかのハッチングがトリックでした。 –

1

矩形の補間が必要な場合は、四角形を四角形で描くことができます(例の画像に表示される四角形のように)。プロットエッジの座標はxlim()ylim()で得ることができます。

私はmatplotlibのは、多角形の外側を塗装する方法を提供することを確認していない...