7

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.

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

Hannah Fry
  • 193
  • 1
  • 7
  • I haven't worked with patches, but is there a way they can be added together? – Thomas K Nov 14 '11 at 18:26
  • Incidentally, if you're doing something requiring a map, I assume you've found basemap, a matplotlib extension for drawing maps? – Thomas K Nov 14 '11 at 18:27
  • Thank you Thomas - yes, I have found basemap. It is great for plotting geolocated points/inter-country flows etc, and actually would work well in this example. Byt I haven't yet worked out how to create plots like KDE's which can align with the map boundary, and I've been looking for a more general solution. – Hannah Fry Nov 15 '11 at 10:47

1 Answers1

8

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')

Before the patches: enter image description here After the patches: enter image description here

Yann
  • 33,811
  • 9
  • 79
  • 70
  • No problem @hannah-fry, if you consider that your "answer", then please check it on the left. Otherwise hopefully someone can give you a more specific answer. – Yann Nov 15 '11 at 13:50
  • I'm trying to do it using pandas plot but the clip is not done. Does anyone know why? I'm doing: `imForWales = df.plot(x ='x', y='y', kind = 'scatter')` – Miguel Gonzalez Nov 30 '20 at 15:44