使用 matplotlib 填充区域的补集
我目前正在使用 Python 和 matplotlib 实现一些东西。我知道如何绘制多边形以及如何填充它们,但是如何填充除多边形内部之外的所有内容?为了更清楚起见,我想修改下面使用 axhspan 和 axvspan 获得的结果,通过裁剪水平和垂直红线以获得一个红色矩形(外面的所有内容都像现在一样被阴影化):
I'm currently implementing something with Python and matplotlib. I know how to draw polygons and also how to fill them, but how do I fill everything except the interior of a polygon? To be clearer, I'd like to modify the result below, obtained using axhspan
's and axvspan
's, by clipping the horizontal and vertical red lines so as to obtain a red rectangle (outside which everything is hatched as it is now):
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这篇文章本质上提出(并回答)这个问题。查看已接受答案中的“编辑 2”。它描述了如何创建绘图边界大小的矢量多边形,以及如何在其中创建孔以匹配您想要补充的形状。它通过分配定义笔移动时是否绘制的行代码来实现此目的。
以下是上述帖子中与此问题相关的部分:
This post asks (and answers) essentially this question. Look at 'Edit 2' in the accepted answer. It describes how to create a vector polygon the size of your plot bounds and then how to create a hole in it to match the shape you want to complement. It does this by assigning line codes that define whether or not the pen draws when it moves.
Here is the portion of the above-referenced post that is relevant to this question:
如果您只需要一个矩形的补集,则可以在其周围绘制 4 个矩形(如示例图像中可见的 4 个矩形)。绘图边缘的坐标可以通过
xlim()
和ylim()
获得。我不确定 Matplotlib 是否提供了一种绘制多边形外部的方法......
If you only need the complement of a rectangle, you could instead draw 4 rectangles around it (like the 4 rectangles that are visible in your example image). The coordinates of the plot edges can be obtained with
xlim()
andylim()
.I am not sure that Matplotlib offers a way of painting the outside of a polygon…