如何在matplotlib中使用自定义填充填充多边形?

Jos*_*iah 10 python image matplotlib polygons hatchstyle

我正在使用python和matplotlib来创建几个封闭的多边形.然后我需要用填充物填充它们,这可以通过set_hatch完成.

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中.

GBy*_*GBy 8

您可以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()
Run Code Online (Sandbox Code Playgroud)

赠送:

在此输入图像描述