使用matplotlib中的几个补丁剪辑图像 [英] Clip an image using several patches in matplotlib

查看:49
本文介绍了使用matplotlib中的几个补丁剪辑图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 pylab 中有一个情节,我想将其剪辑到英国地图的边界.

I have a plot in pylab which I want to clip to the borders of a map of the UK.

我还制作了一系列补丁,其中包含每个国家/地区的轮廓:一个用于英格兰,一个用于威尔士等.

I've also made a series of patches which contain the outlines of each country: one for England, one for Wales etc.

将情节剪辑一个补丁效果很好:

Clipping the plot one patch works brilliantly:

fig = plt.figure()
ax = fig.add_subplot(111)
im = ax.scatter(x,y,c = z)
ax.add_patch(patch)
im.set_clip_path(patch)

但是,如果我尝试做一个以上,它对我一无所有-可以理解,因为每个国家的地块都不同时存在.

But if I try and do it for more than one, it leaves me with nothing - understandably, since no part of the plot is within each country simultaneously.

有谁知道我如何使用OR"类型的语句进行剪辑?(即,不要在此补丁程序或此补丁程序之内等剪辑).

Does anyone know how I can clip using an 'OR' type statement? (ie. don't clip if within this patch or this one etc).

推荐答案

我认为您可以通过制作多个散点图来实现这一点,每个散点图都有一个独特的补丁(例如一个有英格兰,一个有爱尔兰等).尽管这可能不是您所要求的,即有人知道我如何使用 'OR' 类型语句进行剪辑吗?",但它应该具有相同的效果:

I think you can do this by making multiple scatter plots, clipping each one with a unique patch (eg one has England, one has Ireland, etc). Though this might not be what you asked for, ie "Does anyone know how I can clip using an 'OR' type statement?", it should have the same effect:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches

np.random.seed(101)
x = np.random.random(100)
y = np.random.random(100)

fig = plt.figure()
ax = fig.add_subplot(111)
imForEngland = ax.scatter(x,y)
fig.savefig('beforeclip.png')
imForWales = ax.scatter(x,y)
england = patches.Circle((.75,.75),radius=.25,fc='none')
wales = patches.Circle((.25,.25),radius=.25,fc='none')
ax.add_patch(england)
ax.add_patch(wales)
imForEngland.set_clip_path(england)
imForWales.set_clip_path(wales)

fig.savefig('afterclip.png')

在补丁之前:补丁后:

这篇关于使用matplotlib中的几个补丁剪辑图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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