gansub
gansub

Reputation: 1174

Matplotlib - how to superimpose a contour map with coastlines and countries

I have this python script that plots a contour map of geopotential heights -

nc_f = './hgt_500_2014_12_5_00Z.nc'  # Your filename
nc_fid = Dataset(nc_f, 'r')

lats = nc_fid.variables['lat'][:]  # extract/copy the data

lons = nc_fid.variables['lon'][:]

time = nc_fid.variables['time'][:]
hgt = nc_fid.variables['hgt'][:]  # shape is time, lat, lon as shown above

x, y = np.meshgrid(lons, lats,copy=False)

rbf = scipy.interpolate.Rbf(x, y, hgt, function='linear')
zi = rbf(x, y)
plt.contour(x,y,zi)
plt.show()

I want to be able to superimpose this plot with coastlines and countries. I tried this but this gives me the coastlines and countries but the geopotential height contours are missing

 m = Basemap(width=5000000,height=3500000,
        resolution='l',projection='stere',\
        lat_ts=40,lat_0=lat_0,lon_0=lon_0)


 x, y = np.meshgrid(lons, lats,copy=False)

 rbf = scipy.interpolate.Rbf(x, y, hgt, function='linear')
 zi = rbf(x, y)

 cs = m.pcolor(x,y,np.squeeze(hgt))



 m.drawcoastlines()
 m.drawcountries()
 cs = m.contour(x,y,zi,15,linewidths=1.5)

cbar = m.colorbar(cs, location='bottom', pad="10%")
cbar.set_label(hgt_units)

plt.title('500 hPa Geopotential Height')
plt.savefig('testplot.png')
plt.show() 

Upvotes: 3

Views: 2821

Answers (1)

Serenity
Serenity

Reputation: 36695

Your code is totally broken. Look at the example of hgt data:

from netCDF4 import Dataset
import scipy.interpolate
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

nc_f = 'hgt_500.nc'  
nc_fid = Dataset(nc_f, 'r')

lats = nc_fid.variables['lat']  
lons = nc_fid.variables['lon']

time = nc_fid.variables['time']
hgt = nc_fid.variables['hgt']

m = Basemap(width=5000000,height=3500000,
 resolution='l',projection='stere', lat_0 = 60, lon_0 = 70, lat_ts = 40)

m.drawcoastlines()
m.drawcountries()
lons, lats = np.meshgrid(lons, lats)
x, y = m(lons, lats)

# plot the first ZZ of hgt500
clevs = np.arange(400.,604.,4.)
cs = m.contour(x, y, hgt[0] * .1, clevs, linewidths=1.5, colors = 'k')
plt.clabel(cs, inline=1, fontsize=15, color='k', fmt='%.0f') 

# color grid
pcl = m.pcolor(x,y,np.squeeze(hgt[0]*.1))
cbar = m.colorbar(pcl, location='bottom', pad="10%")
cbar.set_label("hPa")

plt.title('500 hPa Geopotential Height')
plt.show() 

Result: enter image description here

Upvotes: 2

Related Questions