Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overlaying a lineCollection on a plot in matplotlib - how to get the two to line up.

I'm trying to do a heat map over a shape file in python. I need to make quite a few of these so don't want to read in the .shp every time.

Instead, I thought I could create a lineCollection instance of the map boundaries and overlay the two images. Problem is - I can't seem to get the two to line up correctly.

Here is the code, where linecol is the lineCollection object.

fig = plt.figure()
ax = fig.add_subplot(111)
ax.contourf(xi,yi,zi)
ax.add_collection(linecol, autolim = False)
plt.show()

Is there an easy way to fix the limits of linecol to match those of the other plot? I've had a play with set_xlim and transforms.Bbox, but can't seem to manage it.

Thank you very much for your help!

like image 863
Hannah Fry Avatar asked Oct 26 '11 14:10

Hannah Fry


1 Answers

Transforms are tricky because of the various coordinate systems involved. See http://matplotlib.sourceforge.net/users/transforms_tutorial.html.

I managed to scale a LineCollection to the appropriate size like this. The key was to realize that I needed to add + ax.transData to the new transform I set on the LineCollection. (When you don't set any transform on an artist object, ax.transData is the default. It converts data coordinates into display coordinates.)

from matplotlib import cm
import matplotlib.pyplot as plt
import matplotlib.collections as mc
import matplotlib.transforms as tx
import numpy as np

fig = plt.figure()

# Heat map spans 1 x 1.
ax = fig.add_subplot(111)
xs = ys = np.arange(0, 1.01, 0.01)
zs = np.random.random((101,101))
ax.contourf(xs, ys, zs, cmap=cm.autumn)

lines = mc.LineCollection([[(5,1), (9,5), (5,9), (1,5), (5,1)]])
# Shape spans 10 x 10. Resize it to 1 x 1 before applying the transform from
# data coords to display coords.
trans = tx.Affine2D().scale(0.1) + ax.transData
lines.set_transform(trans)
ax.add_collection(lines)

plt.show()

(Output here: http://i.stack.imgur.com/hDNN8.png Not enough reputation to post inline.) enter image description here

It should be easy to modify this if you need the shape translated or scaled unequally on x and y.

like image 83
cberzan Avatar answered Oct 19 '22 22:10

cberzan