【问题标题】:How to fill a polygon with a custom hatch in matplotlib?如何在 matplotlib 中使用自定义填充填充多边形?
【发布时间】:2013-06-21 12:44:53
【问题描述】:

我正在使用 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 的解决方案。

【问题讨论】:

  • 这里有custom hatches的例子,但是作者说它很脆。
  • 标准的 set_hatch 有八个不同的阴影,每个可以在至少两种密度下运行,并且可以组合。我认为在你用完孵化组合之前很久,情节就会太混乱了。您是否有具有数十个可用填充的灰度阴影示例?

标签: python image matplotlib polygons hatchstyle


【解决方案1】:

您可以继承 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()

给予:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-15
    相关资源
    最近更新 更多