2013-06-24 99 views
8

我正在使用python和matplotlib來創建幾個封閉的多邊形。然後我需要填充一個艙口,這可以通過set_hatch完成。如何用matplotlib中的自定義圖案填充多邊形?

http://matplotlib.org/api/artist_api.html#matplotlib.patches.Patch.set_hatch

http://matplotlib.org/examples/pylab_examples/hatch_demo.html

不幸的是我與灰度圖像的工作,我需要比默認提供的更多的艙口 - 我寧願提供可替代平鋪一個位圖(或類似圖片)使用密度不同的這些艙口。我打開其他python庫(pyglet,pygame,PIL等),但我更喜歡解決方案是在Python中。

+0

有的[定製艙口]的例子(http://stackoverflow.com/questions/4745937/how-to-decrease-孵化密度在matplotlib?rq = 1)在這裏,但作者說這是脆弱的。 – cphlewis

+1

標準set_hatch具有八個不同的孵化箱,每個孵箱都可以在至少兩種密度下運行,並且可以進行組合。我想在你用完艙口組合之前,情節會讓你感到困惑。您有幾十個可用填充的灰度孵化示例嗎? – cphlewis

回答

6

您可以繼承matplotlib.hatch.Shapes並根據在單位平方[[-0.5,0.5] x [-0.5,0.5]]內繪製的任何參考路徑定義自定義剖面線。

暫定:

import numpy as np 
import matplotlib.hatch 
import matplotlib.pyplot as plt 
from matplotlib.patches import Ellipse, Polygon 


house_path = Polygon(
    [[-0.3, -0.4], [0.3, -0.4], [0.3, 0.1], [0., 0.4], [-0.3, 0.1]], 
    closed=True, fill=False).get_path() 

class CustomHatch(matplotlib.hatch.Shapes): 
    """ 
    Custom hatches defined by a path drawn inside [-0.5, 0.5] square. 
    Identifier 'c'. 
    """ 
    filled = True 
    size = 1.0 
    path = house_path 

    def __init__(self, hatch, density): 
     self.num_rows = (hatch.count('c')) * density 
     self.shape_vertices = self.path.vertices 
     self.shape_codes = self.path.codes 
     matplotlib.hatch.Shapes.__init__(self, hatch, density) 

matplotlib.hatch._hatch_types.append(CustomHatch) 

fig = plt.figure() 
ax = fig.add_subplot(111) 

ellipse = ax.add_patch(Ellipse((0.5, 0.5), 0.3, 0.5, fill=False)) 
ellipse.set_hatch('c') 
ellipse.set_color('red') 
plt.show() 

給予:

enter image description here