2013-06-24 100 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