如何在matplotlib中使用自定义填充填充多边形? [英] How to fill a polygon with a custom hatch in matplotlib?

查看:1752
本文介绍了如何在matplotlib中使用自定义填充填充多边形?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using python and matplotlib to create several closed polygons. I then need to fill them with a hatch, which can be done through set_hatch.

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

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

不幸的是我正在使用灰度图像,我需要比默认提供的更多的阴影 - 我更愿意提供一个可以平铺的位图(或一些类似的图像)而不是使用具有不同密度的这些阴影。

Unfortunately I am working with greyscale images, and I need more hatches than provided by default - I would prefer to provide a bitmap (or some similar image) which could be tiled instead of using these hatches with varying densities.

我对其他python库(pyglet,pygame,PIL等)开放,但是我希望解决方案是在python中。

I am open to other python libraries (pyglet, pygame, PIL, etc) however I would prefer the solution to be in python.

推荐答案

您可以继承 matplotlib.hatch.Shapes 并根据内部绘制的任何参考路径定义自定义填充单位平方[[-0.5,0 .5] x [-0.5,0.5]]。

You can subclass matplotlib.hatch.Shapes and define a custom hatch based on any reference path drawn inside unit square [[-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()

给予:

这篇关于如何在matplotlib中使用自定义填充填充多边形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆