public
Last active

Preparing data to plot contours in Matplotlib's Basemap

  • Download Gist
show_map.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
# More Info: http://davydany.com/post/32287214449/matplotlibs-basemap-plotting-a-list-of-latitude
def show_map(self, a):
# 'a' is of the format [(lats, lons, data), (lats, lons, data)... (lats, lons, data)]
lats = [ x[0] for x in a ]
lons = [ x[1] for x in a ]
data = [ x[2] for x in a ]
lat_min = min(lats)
lat_max = max(lats)
lon_min = min(lons)
lon_max = max(lons)
data_min = min(data)
data_max = max(data)
spatial_resolution = 0.5
fig = plt.figure()
x = np.array(lats)
y = np.array(lons)
z = np.array(data)
xinum = (lat_max - lat_min) / spatial_resolution
yinum = (lon_max - lon_min) / spatial_resolution
xi = np.linspace(lat_min, lat_max + spatial_resolution, xinum) # same as [lat_min:spatial_resolution:lat_max] in matlab
yi = np.linspace(lon_min, lon_max + spatial_resolution, yinum) # same as [lon_min:spatial_resolution:lon_max] in matlab
xi, yi = np.meshgrid(xi, yi)
zi = griddata(x, y, z, xi, yi)
m = Basemap(
projection = 'merc',
llcrnrlat=lat_min, urcrnrlat=lat_max,
llcrnrlon=lon_min, urcrnrlon=lon_max,
rsphere=6371200., resolution='l', area_thresh=10000
)
m.drawcoastlines()
m.drawstates()
m.drawcountries()
lat, lon = m.makegrid(zi.shape[1], zi.shape[0])
x,y = m(lat, lon)
m.contourf(x, y, zi)
plt.show()

Very useful, thanks for sharing.

You might need to switch lons and lats for x and y coordinates:

https://gist.github.com/oblakeobjet/7546272

Miha

Very useful work but it would have been more useful to me if you showed how to read in the data, am very very novice to matplotlib and reading all day long to make sense of every small thing.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.