def get_era_winds(m, rawdatapath, start_year, end_year, start_month, end_month, xyres): wind_data = Dataset(rawdatapath+'/WINDS/ERA/DATA/ERAI_WINDS_MONTHLY_1979-2014.nc', 'r') lats = wind_data.variables['latitude'][::-1] lons = wind_data.variables['longitude'][:] time = wind_data.variables['time'][:]/(24.*30.) time = time-time[0] time=time.reshape(time.shape[0]/12,12) u10 = wind_data.variables['u10'][:, ::-1, :] v10 = wind_data.variables['v10'][:, ::-1, :] u10=u10.reshape(u10.shape[0]/12, 12,u10.shape[1],u10.shape[2]) v10=v10.reshape(v10.shape[0]/12, 12, v10.shape[1],v10.shape[2]) u10_winter_mean= np.mean(u10[start_year-1979:end_year-1979+1,start_month:end_month+1], axis=tuple(range(0, 2))) v10_winter_mean= np.mean(v10[start_year-1979:end_year-1979+1,start_month:end_month+1], axis=tuple(range(0, 2))) u10_winter_meanS, lonsS = shiftgrid(180.,u10_winter_mean,lons,start=False) v10_winter_meanS, lonsS = shiftgrid(180.,v10_winter_mean,lons,start=False) u10_winter_meanSC, lonsSC = addcyclic(u10_winter_meanS, lonsS) v10_winter_meanSC, lonsSC = addcyclic(v10_winter_meanS, lonsS) xyres=100 xvel,yvel,xptsW,yptsW = m.transform_vector(u10_winter_meanSC,v10_winter_meanSC,lonsSC,lats,xyres,xyres,returnxy=True,masked=True) wind_speed = sqrt((xvel**2) + (yvel**2)) wind_speed = sqrt((xvel**2) + (yvel**2)) return xptsW, yptsW, xvel, yvel, wind_speed
def updatefig(*args): global vrtspec, divspec, thetaspec, CS1, CS2, txt1, txt2, t t += model.dt vrtspec, divspec, thetaspec = model.rk4step(vrtspec, divspec, thetaspec) data1, lons1dx = addcyclic(model.vrt[:, :, 1], lons1d) data2, lons1dx = addcyclic(model.theta, lons1d) # remove old contours, add new ones. for c in CS1.collections: c.remove() CS1 = m.contourf(x, y, data1, levs1, cmap=plt.cm.spectral, extend='both', ax=ax1) for c in CS2.collections: c.remove() CS2 = m.contourf(x, y, data2, levs2, cmap=plt.cm.spectral, extend='both', ax=ax2) # update titles. txt1.set_text('Upper Level Vorticity (T%s, hour %6.2f)' % (ntrunc, t / 3600.)) txt2.set_text('Temperature (T%s, hour %6.2f)' % (ntrunc, t / 3600.))
def region_plot(fname, fname2, time, output_dir, julday): ncfile = nc.Dataset(fname,'r') fig = plt.figure(figsize=(20.48,10.24)) ax = plt.axes([0,0,1,1],frameon=False) ax.set_axis_off() # set up a Basemap latrng = (-90.0,90.0) lonrng = (0,360) m = Basemap(projection='cyl',llcrnrlat=latrng[0],urcrnrlat=latrng[1], llcrnrlon=lonrng[0],urcrnrlon=lonrng[1],resolution='h', area_thresh=800,fix_aspect=False) lats = ncfile.variables["yu_ocean"][:] lons = ncfile.variables["xu_ocean"][:] u = ncfile.variables["u"][time,0,:,:] ncfile2 = nc.Dataset(fname2,'r') v = ncfile2.variables["v"][time,0,:,:] lons2 = lons u = ma.array(u) u = ma.masked_where(u <= -10.0, u) u = ma.masked_where(u >= 10.0, u) u = ma.masked_where(u == 0.0, u) u, lons = addcyclic(u, lons) v = ma.array(v) v = ma.masked_where(v <= -10.0, v) v = ma.masked_where(v >= 10.0, v) v = ma.masked_where(v == 0.0, v) v, lons2 = addcyclic(v, lons2) field = ((u**2 + v**2)**0.5) field = np.log(field) x,y = m(*np.meshgrid(lons[:],lats[:])) # cm.Blues looks pretty good colorMap = mpl.cm.Blues m.drawmapboundary(fill_color='white') nlevs = 256 clevs = np.linspace(-4.0,0.5,num=nlevs) cs = m.contourf(x,y,field, levels=clevs, cmap=colorMap, extend='both', norm=mpl.colors.normalize(),antialiased=False ) m.fillcontinents(color='black', lake_color='black', zorder=1) save_file = "%s/%f.png" % (output_dir,julday) plt.savefig(save_file) ncfile.close()
def plot_single_member(z, inens, count): print z.shape col = mod(count, 5) + 1 row = (count / 5) + 1 # some plot parameters llim = 6 lby = 1 tby = 1 levs = np.arange(-llim, llim + lby, lby) cticks = np.arange(-llim, llim + tby, tby) # make cyclic for plotting (add the first longitude + its data to the end) ibase, ilon = addcyclic(z, lon) icbase, iclon = addcyclic(z, lon) # set up grid for plotting glon, glat = np.meshgrid(ilon, lat) cmap = cm.bwr cnorm = colors.Normalize(cmap, clip=False) cmap.set_under(color=cmap(0.0), alpha=1.0) cmap.set_over(color=cmap(1.0), alpha=1.0) # lat/lon boundaries for regions llat = -90 ulat = 90 llon = -180 ulon = 180 map = Basemap(projection='cyl', llcrnrlat=llat, urcrnrlat=ulat, llcrnrlon=llon, urcrnrlon=ulon, fix_aspect=False) # cylindrical is regular in latitude/longitude so no complicated mapping onto map coordinates x, y = map(glon, glat) cols = ccol.custom_colors('grads') ax = plt.subplot2grid((4, 5), (row - 1, col - 1)) #, colspan=1) cplot = map.contourf(x, y, ibase, levs, extend="both", cmap=cols) # plot coastlines, draw label meridians and parallels. map.drawcoastlines(linewidth=1, color="black") map.drawmapboundary() plt.title(str(inens), x=0.08, y=1.02) return (cplot, cticks)
def doplot(nc_file=None,varname=None,vmin=None,vmax=None, title=None): lons=nc_file.variables['lon'][...] lats=nc_file.variables['lat'][...] vals=nc_file.variables[varname] vals.set_auto_maskandscale(True) vals=vals[...] vals,lons=shiftgrid(180.,vals,lons,start=False) vals,lons=addcyclic(vals,lons) fig,ax = plt.subplots(1,1) ax.cla() cmap=cm.RdBu_r cmap.set_over('y') cmap.set_under('k') the_norm=Normalize(vmin=vmin,vmax=vmax,clip=False) params=dict(projection='moll',lon_0= 0,resolution='c') m = Basemap(**params) x, y = m(*np.meshgrid(lons, lats)) im=m.pcolormesh(x,y,vals,cmap=cmap,norm=the_norm,ax=ax) cb=m.colorbar(im,extend='both',location='bottom') m.drawcoastlines() m.drawparallels(np.arange(-90.,120.,30.)) m.drawmeridians(np.arange(0.,420.,60.)) ax.set_title(title) return fig,m,ax,vals,lons
def plot(self): self.data, lonwrap = addcyclic(self.data, self.lons) # Sort latitudes and data lat_idx = np.argsort(self.lats) self.lats = self.lats[lat_idx] self.data = self.data[lat_idx] data_lon_min = min(lonwrap) data_lon_max = max(lonwrap) data_lat_min = min(self.lats) data_lat_max = max(self.lats) new_lons = np.arange(data_lon_min - 1.0, data_lon_max + 1.0, 1.0) new_lats = np.arange(data_lat_min - 1.0, data_lat_max + 1.0, 1.0) x, y = self.m(*np.meshgrid(new_lons[:], new_lats[:])) # Two pass interpolation to deal with the mask. # First pass does bilinear, the next does nearest neighbour # interpolation. # It's not clear this is working, and the problem is likely # solved by ensuring the right mask is used! data_bl = interp(self.data, lonwrap[:], self.lats[:], x, y, order=1) data_nn = interp(self.data, lonwrap[:], self.lats[:], x, y, order=0) data_bl[data_nn.mask == 1] = data_nn[data_nn.mask == 1] if self.parameters.has_key("color_levels"): self.__print_custom_color_plot(x, y, data_bl) else: self.__print_cmap_plot(x, y, data_bl) return self.main_render
def plotter(pdata, colormax=1, colormin=-999, title=''): lon = ncread('/network/aopp/hera/mad/bakerh/HAPPI/HadAM3P-N96/All-Hist/mon/tas/item3236_monthly_mean_a011_2006-01_2016-12.nc', 'longitude0') lat = ncread('/network/aopp/hera/mad/bakerh/HAPPI/HadAM3P-N96/All-Hist/mon/tas/item3236_monthly_mean_a011_2006-01_2016-12.nc', 'latitude0') #lat = ncread('/network/aopp/hera/mad/bakerh/HAPPI/HadAM3P-N96/Plus15-Future_LCO2/day/ua/item15201_daily_mean_a00b_2090-01_2100-12.nc', 'latitude1') if colormin == -999: colormin = -colormax pdata, lon = shiftgrid(180., pdata, lon, start=False) pdata, lon = addcyclic(pdata, lon) meshlon, meshlat = np.meshgrid(lon, lat) m = Basemap(projection='cyl', llcrnrlat=-90, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180, resolution='c') m.drawcoastlines() m.drawmapboundary() x, y = m(meshlon, meshlat) mycmap2 = plt.cm.YlOrRd(np.arange(256)) mycmap1 = plt.cm.Blues_r(np.arange(256)) my_cmap = np.concatenate((mycmap1, mycmap2), axis=0) my_cmap[230:282, :] = 1 if precip == 'yes': my_cmap = my_cmap[::-1] newcmap = mpl.colors.LinearSegmentedColormap.from_list("newjet", my_cmap) ctrs = np.linspace(colormin, colormax, 17) plot = m.contourf(x, y, pdata, ctrs, cmap=newcmap, vmin=np.min(ctrs), vmax=np.max(ctrs), extend='both') plt.title(title, y=1) plt.show() return plot
def draw_basemap(nc_ds, dt_time, lons, lats, nc_var): """Plot of global temperature on our random day""" # fig = pyplot.figure() # fig.subplots_adjust(left=0., right=1., bottom=0., top=0.9) # Setup the map. See http://matplotlib.org/basemap/users/mapsetup.html # for other projections. # m = Basemap(projection='moll', llcrnrlat=-90, urcrnrlat=90, llcrnrlon=0, urcrnrlon=360, resolution='c', lon_0=0) m = Basemap(projection='cyl', resolution='c', lon_0=0) m.drawcoastlines() m.drawmapboundary() time_idx = conf['time_idx'] # Make the plot continuous ds_cyclic, lons_cyclic = addcyclic(nc_ds[time_idx, :, :], lons) # Shift the grid so lons go from -180 to 180 instead of 0 to 360. pre_cyclic, lons_cyclic = shiftgrid(180., ds_cyclic, lons_cyclic, start=False) # Create 2D lat/lon arrays for Basemap lon2d, lat2d = numpy.meshgrid(lons_cyclic, lats) # Transforms lat/lon into plotting coordinates for projection x, y = m(lon2d, lat2d) # Plot of pre with 11 contour intervals cs = m.contourf(x, y, ds_cyclic, 20, cmap=pyplot.cm.Spectral_r) cbar = pyplot.colorbar(cs, orientation='horizontal', shrink=0.9) dot_time = dt_time[time_idx] # cbar.set_label pyplot.title(f"Global {nc_var} for {dot_time.year}.{dot_time.month}") pyplot.show()
def plot(self): self.data, lonwrap = addcyclic(self.data, self.lons) # Sort latitudes and data lat_idx = np.argsort(self.lats) self.lats = self.lats[lat_idx] self.data = self.data[lat_idx] data_lon_min = min(lonwrap) data_lon_max = max(lonwrap) data_lat_min = min(self.lats) data_lat_max = max(self.lats) new_lons = np.arange(data_lon_min - 1.0, data_lon_max + 1.0, 1.0) new_lats = np.arange(data_lat_min - 1.0, data_lat_max + 1.0, 1.0) x, y = self.m(*np.meshgrid(new_lons[:], new_lats[:])) # Two pass interpolation to deal with the mask. # First pass does bilinear, the next does nearest neighbour # interpolation. # It's not clear this is working, and the problem is likely # solved by ensuring the right mask is used! data_bl = interp(self.data, lonwrap[:], self.lats[:], x, y, order=1) data_nn = interp(self.data, lonwrap[:], self.lats[:], x, y, order=0) data_bl[data_nn.mask == 1] = data_nn[data_nn.mask == 1] if self.parameters.has_key('color_levels'): self.__print_custom_color_plot(x, y, data_bl) else: self.__print_cmap_plot(x, y, data_bl) return self.main_render
def makePlot(projection, field, lat, lon, fig_title, title, levels, cmap): # This function makes a lat/lon plot of given field. ########################################################################### # Projection = The projection of basemap you want. Used in base_map function. # field = The field you want to plot. # lat = latitude of the field. # lon = longitude of the field. # fig_title = title of the figure. # levels = putting the values of your plotting limits. # cmap = The colormap you would like to use for the specific plot. ########################################################################### fig = plt.figure(fig_title) w = 16 h = 8 fig.set_size_inches(w, h) fig.patch.set_facecolor('white') m = cartopy_map(projection) # This calls the previous function to # generate the projection of choosen cartopy map. field, lon = basemap.addcyclic(field, lon) field, lon = basemap.shiftgrid(180, field, lon, start=False) lon, lat = np.meshgrid(lon, lat) cf = m.contourf(lon, lat, field, 20, cmap=cmap, levels=levels, extend='both', transform=ccrs.PlateCarree()) cb = plt.colorbar(cf, ticks=levels[::2]) cb.ax.tick_params(labelsize=30) currentAxis = plt.gca() regionleftcorners = [0,-20,-90,-20,-130,20,95,-35,-35,15] for i in range(0,len(regionleftcorners),2): currentAxis.add_patch(Rectangle((regionleftcorners[i],regionleftcorners[i+1],), 10, 10,fc = "None", color ='black',linewidth = 2,linestyle="-")) plt.title(title, fontsize = 32) plt.tight_layout(pad=0.3, h_pad=0.3, w_pad=0.3) plt.show()
def test_run_hgt(): #long term mean fname_mean = '/data01/forONR/hgt.mon.1981-2010.ltm.nc' lev_500 = 5 #level of 500hPa month = 8 #august dataMean = netCDF4.Dataset(fname_mean,'r') hgtMean = dataMean.variables['hgt'][month,lev_500,:,:] #lat,lon #hgtMean += dataMean.variables['hgt'][month-1,lev_500,:,:] #hgtMean += dataMean.variables['hgt'][month-2,lev_500,:,:] #hgtMean /= 3. latMean = dataMean.variables['lat'][:]*np.pi/180. #stored in degrees! lonMean = dataMean.variables['lon'][:]*np.pi/180. dataMean.close() nlat = len(latMean) nlon = len(lonMean) var = np.zeros((nlat,nlon), dtype=float) #mpas files #fnames = [] fnames = sorted(glob.glob('/arctic1/nick/cases/vduda/x4/x4.t.output.2006-08-*')) fnames.extend(sorted(glob.glob('/arctic1/nick/cases/vduda/x4.t.output.2006-08-15*'))) #fnames = sorted(glob.glob('/arctic1/nick/cases/vduda/x4/*.output.2006-08*')) counter = 0 for iFile, fpath in enumerate(fnames): data = output_data.open_netcdf_data(fpath) nEdgesOnCell = data.variables['nEdgesOnCell'][:]; cellsOnCell = data.variables['cellsOnCell'][:]-1; latCell = data.variables['latCell'][:]; lonCell = data.variables['lonCell'][:]; nTimes = len(data.dimensions['Time']) #nTimes = 1 #3 nCells = len(latCell) geop_mpas = np.zeros(nCells,dtype=float) for iTime in xrange(nTimes): #get average value for mesh over these times so can even anomaly different meshes together output_data.print_xtime(data, iTime) hgt_mpas = data.variables['height_500hPa'][iTime,:] #average here to avoid summing to large number over many times geop_mpas += mpas_hgt2geopotential(nCells, hgt_mpas, latCell)/nTimes llMap = makeMap_ll2mpas(latMean, lonMean, latCell, lonCell, nEdgesOnCell, cellsOnCell) var += calc_diff_field(hgtMean, geop_mpas, llMap, nlat, nlon) #print var counter = counter+1 data.close() var /= counter #var = hgtMean # add wrap-around point in longitude. var, lonMean = addcyclic(var, lonMean) np.savez('tmp.dat',var,latMean,lonMean) lats,lons = np.meshgrid(latMean, lonMean) lats *= 180./np.pi; lons *= 180./np.pi plot_anomaly_ll(lats, lons, np.transpose(var))
def __call__(self, field, lon, lat): """ input field on regular lat-lon grid output field on regular projection grid """ if len(field.shape) == 2: field, lon = basemap.addcyclic(field, lon) field, lon = basemap.shiftgrid(180, field, lon, start=False) self.field = self.m.transform_scalar(field, lon, lat, self.nx, self.ny) elif len(field.shape) == 3: n = field.shape[0] self.field = np.zeros((n, self.ny, self.nx), dtype='f') for l in range(n): field1, lon1 = basemap.addcyclic(field[l], lon) field1, lon1 = basemap.shiftgrid(180, field1, lon1, start=False) self.field[l] = self.m.transform_scalar( field1, lon1, lat, self.nx, self.ny) elif len(field.shape) == 4: n0 = field.shape[0] n1 = field.shape[1] if hasattr(field, 'mask'): self.field = np.ma.zeros((n0, n1, self.ny, self.nx), dtype=float) else: self.field = np.zeros((n0, n1, self.ny, self.nx), dtype=float) print 'LambertProjector: Projecting 4D field' m = ProgressMeter(total=n0 * n1) for l0 in range(n0): for l1 in range(n1): field1, lon1 = basemap.addcyclic(field[l0, l1], lon) field1, lon1 = basemap.shiftgrid(180, field1, lon1, start=False) self.field[l0, l1] = self.m.transform_scalar( field1, lon1, lat, self.nx, self.ny) m.update(1) return self.field
def _prune_geogr_data(self, plotdata): if not self._map: self._draw_init() # add wrap-around point in longitude. reviseddata, lons = addcyclic(plotdata, self._data.lons) lons, lats = np.meshgrid(lons, self._data.lats) # adjust longitude point mismatch for negative values in map lons, reviseddata = self._map.shiftdata(lons, datain=reviseddata) return lons, lats, reviseddata
def maplot_orog(pdata, u, v, lat, lon, title=''): """ Plots input grid with map of world overlaid Parameters ---------- plotdata: array data being plotted title: str optional title """ from mpl_toolkits.basemap import Basemap, shiftgrid, addcyclic import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt plt.figure() pdata, lon1 = shiftgrid(180., pdata, lon, start=False) pdata, lon1 = addcyclic(pdata, lon1) u, lon1 = shiftgrid(180., u, lon, start=False) u, lon1 = addcyclic(u, lon1) v, lon = shiftgrid(180., v, lon, start=False) v, lon = addcyclic(v, lon) meshlon, meshlat = np.meshgrid(lon, lat) m = Basemap(projection='cyl', llcrnrlat=-90, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180, resolution='c') m.drawcoastlines() m.drawmapboundary() x, y = m(meshlon, meshlat) plot = m.contour(x, y, pdata, np.array([-3,-2.5,-2,-1.5,-1,-.5,.5,1,1.5,2,2.5,3])*1e-2, colors='k') #plt.quiver(x[::3, ::3], y[::3, ::3], u[::3, ::3], v[::3, ::3]) b = plt.colorbar(plot, orientation='horizontal', aspect=50, shrink=0.75, spacing='proportional') b.set_label(label=r'$\omega$ (Pa s$^{-1}$)') parallels = m.drawparallels(np.arange(-90., 91., 15.)) meridians = m.drawmeridians(np.arange(-180., 181., 30)) m.drawparallels(parallels, labels=[True, True, True, True]) m.drawmeridians(meridians, labels=[True, True, True, True]) plt.title(title, y=1.08) plt.show()
def maplot(pdata, colormax=1, colormin=-999, mask='no', title='', precip='no'): """ Plots input grid with map of world overlaid Parameters ---------- plotdata: array data being plotted title: str optional title """ from mpl_toolkits.basemap import Basemap, shiftgrid, addcyclic import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from netcdfread import ncread if colormin == -999: colormin = -colormax lon = ncread('/network/aopp/hera/mad/bakerh/HAPPI/HadAM3P-N96/All-Hist/mon/tas/item3236_monthly_mean_a011_2006-01_2016-12.nc', 'longitude0') lat = ncread('/network/aopp/hera/mad/bakerh/HAPPI/HadAM3P-N96/All-Hist/mon/tas/item3236_monthly_mean_a011_2006-01_2016-12.nc', 'latitude0') #lat = ncread('/network/aopp/hera/mad/bakerh/HAPPI/HadAM3P-N96/Plus15-Future_LCO2/day/ua/item15201_daily_mean_a00b_2090-01_2100-12.nc', 'latitude1') plt.figure() if mask == 'yes': lsm = ncread('/home/bakerh/Documents/DPhil/CPDN/\ Weather-at-Home_ancilmaker-master/lsm_n96_add.nc', 'lsm')[0, 0, :] pdata = np.ma.masked_array(pdata, mask=np.logical_not(lsm)) pdata, lon = shiftgrid(180., pdata, lon, start=False) pdata, lon = addcyclic(pdata, lon) meshlon, meshlat = np.meshgrid(lon, lat) m = Basemap(projection='cyl', llcrnrlat=-90, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180, resolution='c') m.drawcoastlines() m.drawmapboundary() x, y = m(meshlon, meshlat) mycmap2 = plt.cm.YlOrRd(np.arange(256)) mycmap1 = plt.cm.Blues_r(np.arange(256)) my_cmap = np.concatenate((mycmap1, mycmap2), axis=0) my_cmap[230:282, :] = 1 if precip == 'yes': my_cmap = my_cmap[::-1] newcmap = mpl.colors.LinearSegmentedColormap.from_list("newjet", my_cmap) ctrs = np.linspace(colormin, colormax, 17) plot = m.contourf(x, y, pdata, ctrs, cmap=newcmap, vmin=np.min(ctrs), vmax=np.max(ctrs), extend='both') b = plt.colorbar(plot, orientation='horizontal', aspect=50, shrink=0.75, spacing='proportional') b.set_label(label=r'pr (mm day$^{-1}$)') parallels = m.drawparallels(np.arange(-90., 91., 15.)) meridians = m.drawmeridians(np.arange(-180., 181., 30)) m.drawparallels(parallels, labels=[True, True, True, True]) m.drawmeridians(meridians, labels=[True, True, True, True]) plt.title(title, y=1.08) plt.show()
def shade_coord(xin, yin, datain=None, lon0=None): from mpl_toolkits.basemap import Basemap, shiftgrid, addcyclic from mcmath import edges # invert lat coords if they are descending instead of ascending if yin[-1] < yin[0]: yin = yin[::-1] if datain is not None: ydimloc = np.where(yin.size == np.array(datain.shape))[0] if len(ydimloc) == 0: raise MCPlotError( "no dimension in 'datain' matches length of 'yin'") y_ind = [] for i in xrange(datain.ndim): y_ind.append(slice(None)) y_ind[ydimloc[0]] = slice(None, None, -1) datain = datain[y_ind] yedg = edges(yin) # convert xin to -180:180 range; roll and addcyclic as needed to have lon0 as central lon xedg = edges(xin) xspan = xedg[-1] - xedg[0] if ((xspan < 365.) & (xspan > 355.)): xin = np.where(xin >= 180, xin - 360, xin) roll_ind = np.where(xin < np.roll(xin, 1))[0] if len(roll_ind) == 0: raise MCPlotError("can't find pivot between +180 and -180 in xin") xin = np.roll(xin, -roll_ind) if datain is not None: xdimloc = np.where(xin.size == np.array(datain.shape))[-1] if len(xdimloc) == 0: raise MCPlotError( "no dimension in 'datain' matches length of 'xin'") datain = np.roll(datain, -roll_ind, axis=xdimloc) if (lon0 is not None): (datain, xin) = addcyclic(datain, xin) (datain, xin) = shiftgrid(lon0 - 180, datain, xin) xedg = edges(xin) ## Fix for keeping the squares near the edges of global maps filled just to the edge (map boundary) if (lon0 is not None): if xedg[0] < (lon0 - 180): xedg[0] = lon0 - 180 if xedg[-1] > (lon0 + 180): xedg[-1] = lon0 + 180 # return [xedg,yedg,datain,xin,yin] else: xedg = edges(xin) return [xedg, yedg, datain, xin, yin]
def project_SkyMap_Mollweide(skymap, Pnorm=1, Qnorm=1, Ppath=None, Qpath=None): Pw, lonsw = addcyclic(skymap.P, skymap.sky.lons) Qw, lonsw = addcyclic(skymap.Q, skymap.sky.lons) meshlon, meshlat = pylab.meshgrid(lonsw, skymap.sky.lats) projection = Basemap(projection='moll', lon_0=180, resolution='c') # projection = Basemap( projection='ortho' , lat_0=60 , lon_0=180 , resolution='c' ) projection.drawmapboundary() x, y = projection(meshlon, meshlat) if Ppath == None: pass else: fig = pyplot.figure(figsize=(8, 8)) ax = fig.add_axes([0.05, 0.15, 0.8, 0.8]) projection.contourf(x, y, Pnorm * Pw, 30) projection.drawmeridians(numpy.arange(0, 360, 30)) projection.drawparallels(numpy.arange(-90, 90, 30), labels=[1, 0, 0, 0]) pos = ax.get_position() l, b, w, h = pos.bounds cax = pyplot.axes([l + w + 0.03, b, 0.04, h]) pyplot.colorbar(cax=cax, orientation='vertical', format='%.1e') pylab.savefig(Ppath) if Qpath == None: pass else: fig = pyplot.figure(figsize=(8, 8)) ax = fig.add_axes([0.05, 0.15, 0.8, 0.8]) projection.contourf(x, y, Qnorm * Qw, 30) projection.drawmeridians(numpy.arange(0, 360, 30)) projection.drawparallels(numpy.arange(-90, 90, 30), labels=[1, 0, 0, 0]) pos = ax.get_position() l, b, w, h = pos.bounds cax = pyplot.axes([l + w + 0.03, b, 0.04, h]) pyplot.colorbar(cax=cax, orientation='vertical') pylab.savefig(Qpath) return
def make_map(lat, lon, data): m = Basemap(projection='cyl', llcrnrlat=-90, urcrnrlat=90\ , llcrnrlon=-180, urcrnrlon=180, resolution='c') m.drawcoastlines() m.drawmapboundary() m.drawcountries() m.drawparallels([-90,-60,-30,0,30,60,90], linewidth=0.25) m.drawmeridians([-120,-60,0,60,120], linewidth=0.25) datap, lonp = addcyclic(data, lon) LONS, LATS = np.meshgrid(lonp, lat) x, y = m(LONS, LATS) return m, x, y, datap
def region_plot(fname, time, output_dir, julday): #print "fname = %s, day = %d\n" % (fname, time); ncfile = nc.Dataset(fname,'r') fig = plt.figure(figsize=(20.48,10.24)) ax = plt.axes([0,0,1,1],frameon=False) ax.set_axis_off() # set up a Basemap latrng = (-90.0,90.0) lonrng = (0,360) m = Basemap(projection='cyl',llcrnrlat=latrng[0],urcrnrlat=latrng[1], llcrnrlon=lonrng[0],urcrnrlon=lonrng[1],resolution='h', area_thresh=800,fix_aspect=False) # for mom output lats = ncfile.variables["yt_ocean"][:] lons = ncfile.variables["xt_ocean"][:] field = ncfile.variables["eta_t"][time,:,:] aveNcfile = nc.Dataset('ocean_eta_annual.nc','r') average = aveNcfile.variables["eta_t"][0,:,:] field = field - average field = ma.array(field) field = ma.masked_where(field == -1.0e10, field) field = ma.masked_where(field<= -10,field) field = ma.masked_where(field>= 100, field) field, lons = addcyclic(field, lons) #field_min = np.min(field) #field_max = np.max(field) x,y = m(*np.meshgrid(lons[:],lats[:])) colorMap = colormaps.make_colormap({0.:'#191970', 0.2:'#448BB9', 0.35:'#1e90ff', 0.5:'w', 0.6:'#F8BC4E', 0.7:'#ffa500', 0.8:'#ff8c00',0.9:'#F56D2E', 1.0:'#CC4000'}) m.drawmapboundary(fill_color='white') nlevs = 256 clevs = np.linspace(-0.8,0.8,num=nlevs) cs = m.contourf(x,y,field, levels=clevs, cmap=colorMap, extend='both', norm=mpl.colors.normalize(),antialiased=False ) m.fillcontinents(color='black', lake_color='black', zorder=1) save_file = "%s/%f.png" % (output_dir,julday) plt.savefig(save_file) #plt.show() ncfile.close()
def preplot(): lats = data[0].variables['latitude'][:] lons1 = data[0].variables['longitude'][:] nlats = len(lats) nlons = len(lons1) #cbarunits = 'Mean sea pressure hPa' cbarunits = 'hPa' # create Basemap instance. #m =\ #Basemap(projection='spstere',boundinglat=blat,lon_0=165,resolution='l') m = Basemap(projection='mill', resolution='c', llcrnrlon=0, llcrnrlat=-90, urcrnrlon=360.01, urcrnrlat=20) # add wrap-around point in longitude. results_plot, lons = addcyclic(mydiff, lons1) # find x,y of map projection grid. lons, lats = np.meshgrid(lons, lats) x, y = m(lons, lats) # create figure. fig = plt.figure(figsize=(18, 10)) ax = fig.add_axes([0.09, 0.10, 0.80, 0.80]) #0.5, 0.5, 0.9, 0.85 #levels = [-10, -9.5, -9, -8.5, -8, -7.5, -7, -6.5, -6, -5.5, -5, -4, -3, -2, -1, 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 25] clevs = np.linspace(-8.0, 8.0, 25) orig_cmap = plt.cm.coolwarm cs = m.contourf(x, y, results_plot, clevs, cmap=orig_cmap, extend='both') m.drawcoastlines(linewidth=1.25) #m.fillcontinents(color='0.8') m.drawparallels(np.arange(-80, 81, 20), labels=[1, 0, 0, 0], fontsize=40) m.drawmeridians(np.arange(0, 360, 60), labels=[0, 0, 0, 1], fontsize=40) # add colorbar. #plt.colorbar(orientation='horizontal') #cbar = m.colorbar(pad="15%",location='bottom') #cbar.set_label('hPa', rotation=0, fontsize=30) #tick_locator = ticker.MaxNLocator(nbins=8) #cbar.locator = tick_locator ##cbar.ax.xaxis.set_major_locator(ticker.AutoLocator()) #cbar.ax.tick_params(labelsize=30) #cbar.update_ticks() plt.title(plottitle + ' ' + str(float(myjob) * 0.75 - 3) + 'K', fontsize=55, y=1.02) #plt.show() plt.savefig(filename)
def project_SkyMap_Mollweide( skymap , Pnorm=1 , Qnorm=1 , Ppath=None , Qpath=None ): Pw , lonsw = addcyclic( skymap.P , skymap.sky.lons ) Qw , lonsw = addcyclic( skymap.Q , skymap.sky.lons ) meshlon , meshlat = pylab.meshgrid( lonsw , skymap.sky.lats ) projection = Basemap( projection='moll' , lon_0=180 , resolution='c' ) # projection = Basemap( projection='ortho' , lat_0=60 , lon_0=180 , resolution='c' ) projection.drawmapboundary() x , y = projection( meshlon , meshlat ) if Ppath == None : pass else : fig = pyplot.figure( figsize = (8,8) ) ax = fig.add_axes( [ 0.05 , 0.15 , 0.8 , 0.8 ] ) projection.contourf( x , y , Pnorm*Pw , 30 ) projection.drawmeridians( numpy.arange(0,360,30) ) projection.drawparallels( numpy.arange(-90,90,30) , labels=[1,0,0,0] ) pos = ax.get_position() l , b , w , h = pos.bounds cax = pyplot.axes( [ l+w+0.03 , b , 0.04 , h ] ) pyplot.colorbar( cax=cax , orientation='vertical' , format='%.1e' ) pylab.savefig( Ppath ) if Qpath == None : pass else : fig = pyplot.figure( figsize = (8,8) ) ax = fig.add_axes( [ 0.05 , 0.15 , 0.8 , 0.8 ] ) projection.contourf( x , y , Qnorm*Qw , 30 ) projection.drawmeridians( numpy.arange(0,360,30) ) projection.drawparallels( numpy.arange(-90,90,30) , labels=[1,0,0,0] ) pos = ax.get_position() l , b , w , h = pos.bounds cax = pyplot.axes( [ l+w+0.03 , b , 0.04 , h ] ) pyplot.colorbar( cax=cax , orientation='vertical' ) pylab.savefig( Qpath ) return
def plotMap(self, figdir=''): if not self.gotpix: self.getPixels() lats = self.sky.lats lons = self.sky.lons pixpw, lonsw = addcyclic(self.pixp, lons) pixqw, lonsw = addcyclic(self.pixq, lons) meshlon, meshlat = pylab.meshgrid(lonsw, lats) projection = Basemap(projection='moll', lon_0=180, resolution='c') x, y = projection(meshlon, meshlat) projection.contourf(x, y, pixpw, 30) projection.drawmeridians(numpy.arange(0, 360, 30)) projection.drawparallels(numpy.arange(-90, 90, 30)) projection.drawmapboundary() figname = self.outfileprefix + '-' + self.maptype + 'real.png' pylab.savefig((figdir + figname)) projection.contourf(x, y, pixqw, 30) projection.drawmeridians(numpy.arange(0, 360, 30)) projection.drawparallels(numpy.arange(-90, 90, 30)) projection.drawmapboundary() figname = self.outfileprefix + '-' + self.maptype + 'imag.png' pylab.savefig((figdir + figname))
def plotMap(self,figdir=''): if not self.gotpix: self.getPixels() lats = self.sky.lats lons = self.sky.lons pixpw , lonsw = addcyclic( self.pixp , lons ) pixqw , lonsw = addcyclic( self.pixq , lons ) meshlon, meshlat = pylab.meshgrid( lonsw , lats ) projection = Basemap(projection='moll',lon_0=180,resolution='c') x , y = projection( meshlon , meshlat ) projection.contourf( x,y, pixpw , 30) projection.drawmeridians(numpy.arange(0,360,30)) projection.drawparallels(numpy.arange(-90,90,30)) projection.drawmapboundary() figname = self.outfileprefix + '-' + self.maptype + 'real.png' pylab.savefig( ( figdir + figname ) ) projection.contourf( x,y, pixqw , 30) projection.drawmeridians(numpy.arange(0,360,30)) projection.drawparallels(numpy.arange(-90,90,30)) projection.drawmapboundary() figname = self.outfileprefix + '-' + self.maptype + 'imag.png' pylab.savefig( ( figdir + figname ) )
def shade_coord(xin,yin,datain=None,lon0=None): from mpl_toolkits.basemap import Basemap, shiftgrid, addcyclic from mcmath import edges # invert lat coords if they are descending instead of ascending if yin[-1] < yin[0]: yin = yin[::-1] if datain is not None: ydimloc = np.where(yin.size == np.array(datain.shape))[0] if len(ydimloc) == 0: raise MCPlotError("no dimension in 'datain' matches length of 'yin'") y_ind = [] for i in xrange(datain.ndim): y_ind.append(slice(None)) y_ind[ydimloc[0]] = slice(None,None,-1) datain = datain[y_ind] yedg = edges(yin) # convert xin to -180:180 range; roll and addcyclic as needed to have lon0 as central lon xedg = edges(xin) xspan = xedg[-1] - xedg[0] if ((xspan < 365.) & (xspan > 355.)): xin = np.where(xin >= 180,xin-360,xin) roll_ind = np.where(xin < np.roll(xin,1))[0] if len(roll_ind) == 0: raise MCPlotError("can't find pivot between +180 and -180 in xin") xin = np.roll(xin,-roll_ind) if datain is not None: xdimloc = np.where(xin.size == np.array(datain.shape))[-1] if len(xdimloc) == 0: raise MCPlotError("no dimension in 'datain' matches length of 'xin'") datain = np.roll(datain,-roll_ind,axis=xdimloc) if (lon0 is not None): (datain,xin) = addcyclic(datain,xin) (datain,xin) = shiftgrid(lon0-180,datain,xin) xedg = edges(xin) ## Fix for keeping the squares near the edges of global maps filled just to the edge (map boundary) if (lon0 is not None): if xedg[0] < (lon0-180): xedg[0] = lon0-180 if xedg[-1] > (lon0+180): xedg[-1] = lon0+180 return [xedg,yedg,datain,xin,yin] else: xedg = edges(xin) return [xedg,yedg,datain,xin,yin]
def BuildArray(self,m,img,lon_0): if lon_0 != 180: new_img, new_lons = addcyclic(img,self.lons) new_img, new_lons = shiftgrid(lon_0, img, self.lons, start=False) else: new_img = img new_lons = self.lons transformed_img = m.transform_scalar(new_img, new_lons, self.lats[-1::-1], self.nlon, self.nlat, masked=1.e-5) return transformed_img
def expand_longitude(test_lon, orig_lon, orig_data): """ Makes a cyclic array using basemap and expands the longitudes to give the buffer aroud the edge needed for the area weighted re-gridding. """ import numpy as np from mpl_toolkits.basemap import addcyclic, shiftgrid import copy # shift the grid of the emissions so it fits with the test longitude grid # first, find the value of the orig long grid nearest to the test long grid if len(orig_data.shape) != 2: raise Exception, 'Data array must be two-dimensional' idx = (np.abs(orig_lon - test_lon[0])).argmin() start = orig_lon[idx] orig_data_temp, orig_lon_temp = addcyclic(orig_data, orig_lon) orig_data_temp, orig_lon_temp = shiftgrid(start, orig_data_temp, orig_lon_temp) test_dlon = test_lon[1] - test_lon[0] orig_dlon = orig_lon[1] - orig_lon[0] extra_cells = np.int(test_dlon / orig_dlon) + 2 # NOTE: DATA AND LOGITUDE HAVE BEEN MADE CYCLIC, ORIGIN IS THAT CLOSEST IN ORIG TO THE START OF TEST new_lon = np.linspace(orig_lon_temp[0] - extra_cells*orig_dlon,\ orig_lon_temp[-2]+(extra_cells)*orig_dlon,\ len(orig_lon)+2*extra_cells) lon_index = np.arange(-1 * extra_cells, len(new_lon) - extra_cells, 1, dtype=np.int) new_data = np.zeros((orig_data.shape[0], len(new_lon))) i = 0 while i < len(new_lon): # ignore cyclic grid here for length, since orig_data_temp[0] == orig_data_temp[1], but # we don't want to replicate that new_data[:, i] = copy.deepcopy(orig_data_temp[:, lon_index[i] % orig_data.shape[1]]) i += 1 del idx del i del start del orig_data_temp del orig_lon_temp del test_dlon del orig_dlon del test_lon del orig_lon del orig_data del extra_cells del lon_index return new_lon, new_data
def region_plot(fname, time, output_dir, julday): ncfile = nc.Dataset(fname,'r') fig = plt.figure(figsize=(20,10)) ax = plt.axes([0,0,1,1],frameon=False) ax.set_axis_off() # set up a Basemap latrng = (-90.0,90.0) lonrng = (0,360) m = Basemap(projection='cyl',llcrnrlat=latrng[0],urcrnrlat=latrng[1], llcrnrlon=lonrng[0],urcrnrlon=lonrng[1],resolution='h', area_thresh=800,fix_aspect=False) # for ofam salinity lats = ncfile.variables["yt_ocean"][:] lons = ncfile.variables["xt_ocean"][:] field = ncfile.variables["salt"][time,0,:,:] aveNcfile = nc.Dataset('ocean_salt_annual.nc','r') average = aveNcfile.variables["salt"][0,0,:,:] field = field - average field = ma.array(field) field = ma.masked_where(field == -1.0e10, field) field = ma.masked_where(field<= -10,field) field = ma.masked_where(field>= 100, field) field, lons = addcyclic(field, lons) x,y = m(*np.meshgrid(lons[:],lats[:])) colorMap = colormaps.make_colormap({0.:'#010233', 0.3:'#01034B',0.4:'#02035F',0.42:'#28297B', 0.45:'#3B3D8E', 0.5:'w', 0.55:'#B32222',0.58:'#731515',0.6:'#600202',0.7:'#4B0202', 1.0:'#330101'}) # red to blue m.drawmapboundary(fill_color='white') nlevs = 256 clevs = np.linspace(-2,2,num=nlevs) cs = m.contourf(x,y,field, levels=clevs, cmap=colorMap, extend='both', norm=mpl.colors.normalize(),antialiased=False ) m.fillcontinents(color='black', lake_color='black', zorder=1) save_file = "%s/%f.png" % (output_dir,julday) plt.savefig(save_file) ncfile.close()
def region_plot(fname, time, output_dir, julday): ncfile = nc.Dataset(fname,'r') fig = plt.figure(figsize=(20.48,10.24)) ax = plt.axes([0,0,1,1],frameon=False) ax.set_axis_off() # set up a Basemap latrng = (-90.0,90.0) lonrng = (0,360) m = Basemap(projection='cyl',llcrnrlat=latrng[0],urcrnrlat=latrng[1], llcrnrlon=lonrng[0],urcrnrlon=lonrng[1],resolution='h', area_thresh=800,fix_aspect=False) # for salinity lats = ncfile.variables["yt_ocean"][:] lons = ncfile.variables["xt_ocean"][:] field = ncfile.variables["salt"][time,0,:,:] field = ma.array(field) field = ma.masked_where(field == -1.0e10, field) field = ma.masked_where(field<= -10,field) field = ma.masked_where(field>= 100, field) field, lons = addcyclic(field, lons) #field_min = np.min(field) #field_max = np.max(field) x,y = m(*np.meshgrid(lons[:],lats[:])) # do one with jet colormap colorMap = mpl.cm.jet m.drawmapboundary(fill_color='white') nlevs = 256 clevs = np.linspace(28,38,num=nlevs) cs = m.contourf(x,y,field, levels=clevs, cmap=colorMap, extend='both', norm=mpl.colors.normalize(),antialiased=False ) m.fillcontinents(color='black', lake_color='black', zorder=1) save_file = "%s/%f.png" % (output_dir,julday) plt.savefig(save_file) ncfile.close()
def test_plot(): fname_mean = '/data01/forONR/hgt.mon.1981-2010.ltm.nc' dataMean = netCDF4.Dataset(fname_mean,'r') latMean = dataMean.variables['lat'][:] lonMean = dataMean.variables['lon'][:] dataMean.close() nlat = len(latMean) nlon = len(lonMean) var = np.zeros((nlat,nlon), dtype=float) for iLat in xrange(nlat): for iLon in xrange(nlon): var[iLat, iLon] = lonMean[iLon] #latMean[iLat] var, lonMean = addcyclic(var, lonMean) lats,lons = np.meshgrid(latMean, lonMean) plot_anomaly_ll(lats, lons, np.transpose(var))
def expand_longitude( test_lon,orig_lon,orig_data): """ Makes a cyclic array using basemap and expands the longitudes to give the buffer aroud the edge needed for the area weighted re-gridding. """ import numpy as np from mpl_toolkits.basemap import addcyclic, shiftgrid import copy # shift the grid of the emissions so it fits with the test longitude grid # first, find the value of the orig long grid nearest to the test long grid if len(orig_data.shape) != 2: raise Exception, 'Data array must be two-dimensional' idx = (np.abs(orig_lon-test_lon[0])).argmin() start = orig_lon[idx] orig_data_temp,orig_lon_temp=addcyclic(orig_data,orig_lon) orig_data_temp,orig_lon_temp=shiftgrid(start,orig_data_temp,orig_lon_temp) test_dlon = test_lon[1] - test_lon[0] orig_dlon = orig_lon[1] - orig_lon[0] extra_cells=np.int(test_dlon/orig_dlon)+2 # NOTE: DATA AND LOGITUDE HAVE BEEN MADE CYCLIC, ORIGIN IS THAT CLOSEST IN ORIG TO THE START OF TEST new_lon = np.linspace(orig_lon_temp[0] - extra_cells*orig_dlon,\ orig_lon_temp[-2]+(extra_cells)*orig_dlon,\ len(orig_lon)+2*extra_cells) lon_index = np.arange(-1*extra_cells,len(new_lon)-extra_cells,1,dtype=np.int) new_data = np.zeros((orig_data.shape[0],len(new_lon))) i = 0 while i < len(new_lon): # ignore cyclic grid here for length, since orig_data_temp[0] == orig_data_temp[1], but # we don't want to replicate that new_data[:,i] = copy.deepcopy(orig_data_temp[:,lon_index[i]%orig_data.shape[1]]) i+=1 del idx del i del start del orig_data_temp del orig_lon_temp del test_dlon del orig_dlon del test_lon del orig_lon del orig_data del extra_cells del lon_index return new_lon,new_data
def _meshgrid(self, data_array): """ given some data, returns the np.meshgrid associated lons and lats + addcyclic longitude if proj is 'spstere' or 'npstere' """ latitudes = self.dset_domain['latitudes'].data longitudes = self.dset_domain['longitudes'].data if self.proj in ['npstere','spstere','moll']: """ if north polar or south polar stereographic projection we take care of the discontinuity at Greenwich using the `addcyclic` function of basemap """ data_array, lon = addcyclic(data_array, longitudes) lons, lats = np.meshgrid(lon, latitudes) else: lons, lats = np.meshgrid(longitudes, latitudes) return lons, lats, data_array
def contour(self,arr,nbins,d,fmt=False): if (self.lonmin==0 and self.lonmax==385.5): v,xl = addcyclic(arr,self.x_axis) else: v = arr xl = self.x_axis yl = self.y_axis lon,lat = np.meshgrid(xl,yl) self.x,self.y = self.m(lon, lat) levels = MaxNLocator(nbins=nbins).tick_values(arr.min(),arr.max()) cs = self.m.contour(self.x,self.y,v,levels=levels,colors='black',linewidths=1,liinestyles='solid') if fmt == False: fmt = '%f' else: fmt=ticker.FuncFormatter(fmt) clevels = levels[::d] clb=plt.clabel(cs,clevels,fontsize=7,fmt=fmt)
def __transform_lons(self,bbox,lons,var): """ Take Bounding box longitudes and transform them for sensible Basemap plotting. bbox: Bounding Box ... values will change in there lons: numpy array of longitudes var: numpy array of field to be plotted """ to_360 = lambda x: ( x % 360. ) # Put everything into a range greater 0 right away lon_min = to_360(bbox.lon_min) lon_max = to_360(bbox.lon_max) lons = to_360(lons) # If lon_min is greater than lon_max after transformation if lon_min > lon_max: lon_max += 360. # If both are the same i.e. 360 degree print if lon_min == lon_max: lon_max += 360. # If lon_max greater than 360, remap longitudes to that range if lon_max > 360.: idx = lons < lon_min lons[idx] = lons[idx] + 360. bbox.lon_min = lon_min bbox.lon_max = lon_max # Ensure longitudes are ascending, and shuffle field with same indices idx = np.argsort(lons) lons = lons[idx] var = var[:,idx] var, lons = addcyclic(var,lons) return bbox,lons,var
def shading(self,arr,name,nbins,setorigin=1,cutoff = False,fmt=False): if (self.lonmin==0 and self.lonmax==385.5): v,xl = addcyclic(arr,self.x_axis) else: v = arr xl = self.x_axis yl = self.y_axis lon,lat = np.meshgrid(xl,yl) self.x,self.y = self.m(lon, lat) avg = np.mean(arr) std = np.std(arr) r = 4.5 if cutoff==True: arr = np.where(arr<r*std,arr,r*std) arr = np.where(arr>-1.0*r*std,arr,-1.0*r*std) vmin = arr.min() vmax = arr.max() axis = np.arange(avg-1.8*std,avg+1.8*std,.2*std) if fmt == False: fmt = '%f' else: fmt=ticker.FuncFormatter(fmt) if setorigin==1: self.cmap = shiftedColorMap(self.cmap,midpoint= -vmin/(vmax-vmin)) levels = MaxNLocator(nbins=nbins).tick_values(vmin,vmax) cs = self.m.contourf(self.x,self.y,v,axis,levels=levels,cmap=self.cmap,extend='both') cb = self.m.colorbar(cs,location='bottom',extend='both',spacing='proportional',fraction=0.046,pad=0.30,shrink=0.6,format=fmt) cb.ax.tick_params(direction='out',length=6,width=2,labelsize=7,grid_alpha=0.1) cb.set_label(name,size=15)
def plot_map(self, pscf, boundinglat=-20, axes=[]): if len(axes) == 0: fig, ax = plt.subplots(1, 1, figsize=(6, 6)) cax = fig.add_axes([0.15, 0.06, 0.7, 0.04]) else: fig, ax, cax = axes m = Basemap(projection="spstere", lon_0=180, boundinglat=boundinglat, round=True, ax=ax) data, lonx = addcyclic(pscf.T.values, pscf["Longitude"]) latx, lonx = np.meshgrid(pscf["Latitude"], lonx) lonx, latx = m(lonx, latx) if pscf.max().values <= 1: h = m.contourf(lonx, latx, data.T, levels=np.arange(0, 1.1, 0.1)) else: levels = np.arange(0, pscf.max(), 2) h = m.contourf(lonx, latx, data.T, levels=levels) plt.colorbar(h, cax=cax, orientation="horizontal") m.drawcoastlines(linewidth=1.5) m.drawcountries(linewidth=0.55) ax.set_title(self.station, fontweight="bold") return fig, ax, m
def __init__( self, filename, varname, time_ndx=0, level_ndx=0 ): fh = nc.Dataset(filename, 'r', format='NETCDF4') dims = fh.dimensions if dims.has_key('time') : self.units = fh.variables[varname].units if dims.has_key('ncol') : if fh.variables[varname].ndim == 3 : self.data = numpy.ravel(fh.variables[varname][time_ndx,level_ndx,:]) self.levdep = True else: self.data = numpy.ravel(fh.variables[varname][time_ndx,:]) self.levdep = False self.lon = numpy.ravel(fh.variables["lon"][:]) self.lat = numpy.ravel(fh.variables["lat"][:]) self.structured = False if dims.has_key('lon') and dims.has_key('lat') : if fh.variables[varname].ndim == 4 : self.data = fh.variables[varname][time_ndx,level_ndx,:,:] self.levdep = True else: self.data = fh.variables[varname][time_ndx,:,:] self.levdep = False self.lon = fh.variables["lon"][:] self.lat = fh.variables["lat"][:] self.structured = True # Add longitude cyclic point self.data,self.lon = bm.addcyclic(self.data,self.lon) else : if dims.has_key('ncol') : if fh.variables[varname].ndim == 2 : self.data = numpy.ravel(fh.variables[varname][level_ndx,:]) self.levdep = True else: self.data = numpy.ravel(fh.variables[varname][:]) self.levdep = False self.lon = numpy.ravel(fh.variables["lon"][:]) self.lat = numpy.ravel(fh.variables["lat"][:]) self.structured = False if dims.has_key('lon') and dims.has_key('lat') : if fh.variables[varname].rank == 3 : self.data = fh.variables[varname][level_ndx,:,:] self.levdep = True else: self.data = fh.variables[varname][:,:] self.levdep = False self.lon = fh.variables["lon"][:] self.lat = fh.variables["lat"][:] self.structured = True # Add longitude cyclic point self.data,self.lon = bm.addcyclic(self.data,self.lon) fh.close
#-----------------END CALLING FUNCTION 3----------------- #-----------------BEGIN PLOT----------------- # read lats,lons. lats = data.variables['latitude'][:] lons1 = data.variables['longitude'][:] nlats = len(lats) nlons = len(lons1) # create Basemap instance. m =\ Basemap(projection='spstere',boundinglat=blat,lon_0=165,resolution='l') # add wrap-around point in longitude. prmsl_abs, lons = addcyclic(prmsl_abs, lons1) # find x,y of map projection grid. lons, lats = np.meshgrid(lons, lats) x, y = m(lons, lats) # create figure. fig=plt.figure(figsize=(8,4.5)) ax = fig.add_axes([0.05,0.05,0.9,0.85]) levels = [-12, -11, -10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0.0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] orig_cmap = plt.cm.coolwarm cs = m.contourf(x,y,prmsl_abs,levels,cmap=orig_cmap) #amundsen_low = np.max(prmsl_abs[600:660,680:1160]) #-----------------END PLOT-----------------
limit = np.arange(-5,5.1,0.1) barlim = np.arange(-5,6,5) elif varnames[v] == 'WAFY150': limit = np.arange(-2,2.01,0.05) barlim = np.arange(-2,3,2) fig = plt.figure() for i in range(len(diffruns_mo)): var = diffruns_mo[i] pvar = pruns_mo[i] ax1 = plt.subplot(2,3,i+1) m = Basemap(projection='ortho',lon_0=0,lat_0=89,resolution='l', area_thresh=10000.) var, lons_cyclic = addcyclic(var, lon) var, lons_cyclic = shiftgrid(180., var, lons_cyclic, start=False) lon2d, lat2d = np.meshgrid(lons_cyclic, lat) x, y = m(lon2d, lat2d) pvar,lons_cyclic = addcyclic(pvar, lon) pvar,lons_cyclic = shiftgrid(180.,pvar,lons_cyclic,start=False) climoq,lons_cyclic = addcyclic(climo[i], lon) climoq,lons_cyclic = shiftgrid(180.,climoq,lons_cyclic,start=False) m.drawmapboundary(fill_color='white',color='dimgray',linewidth=0.7) cs = m.contourf(x,y,var,limit,extend='both') cs1 = m.contourf(x,y,pvar,colors='None',hatches=['....'], linewidths=0.4) if varnames[v] == 'Z30': # the interval is 250 m
for i in range(len(experiments)): var = diffruns_djf[i] pvar = pruns_djf[i] climo = wavelist[i] limit = np.arange(-60, 61, 5) barlim = np.arange(-60, 61, 30) ax1 = plt.subplot(1, 3, i + 1) m = Basemap(projection='ortho', lon_0=0, lat_0=90, resolution='l', area_thresh=10000.) var, lons_cyclic = addcyclic(var, lon1) var, lons_cyclic = shiftgrid(180., var, lons_cyclic, start=False) lon2d, lat2d = np.meshgrid(lons_cyclic, lat) x, y = m(lon2d, lat2d) pvar, lons_cyclic = addcyclic(pvar, lon1) pvar, lons_cyclic = shiftgrid(180., pvar, lons_cyclic, start=False) # climo,lons_cyclic = addcyclic(climo,lon) # climo,lons_cyclic = shiftgrid(180.,climo,lons_cyclic,start=False) # lon2dc, lat2dc = np.meshgrid(lons_cyclic, lat) lon2c, lat2c = np.meshgrid(lon, lat) m.drawmapboundary(fill_color='white', color='w', linewidth=0.7) m.drawcoastlines(color='dimgray', linewidth=0.65) cs = m.contourf(x,
for i in range(sst.shape[0]): fig = plt.figure() ax = plt.subplot(111) for txt in fig.texts: txt.set_visible(False) var = sst[i, :, :] m.drawmapboundary(fill_color='k') m.drawcoastlines(color='k', linewidth=0.4) ### Colorbar limits barlim = np.arange(0, 31, 5) ### Make the plot continuous var, lons_cyclic = addcyclic(var, lons) var, lons_cyclic = shiftgrid(180., var, lons_cyclic, start=False) lon2d, lat2d = np.meshgrid(lons_cyclic, lats) x, y = m(lon2d, lat2d) cs = plt.contourf(x, y, var, np.arange(-1.8, 31.1, 1), extend='max') cmap = ncm.cmap('MPL_gnuplot') cs.set_cmap(cmap) t = plt.annotate(r'\textbf{%s}' % yearsqq[i], textcoords='axes fraction', xy=(0, 0), xytext=(0.34, 1.03), fontsize=50, color='w', alpha=0.6)
### Set limits for contours and colorbars limit = np.arange(-100, 100.1, 1) barlim = np.arange(-100, 101, 50) ### Begin plot fig = plt.figure() ax1 = plt.subplot(131) m = Basemap(projection='ortho', lon_0=0, lat_0=89, resolution='l', area_thresh=10000.) var, lons_cyclic = addcyclic(diff_on, lon) var, lons_cyclic = shiftgrid(180., var, lons_cyclic, start=False) lon2d, lat2d = np.meshgrid(lons_cyclic, lat) x, y = m(lon2d, lat2d) pvalue_onq, lons_cyclic = addcyclic(pvalue_on, lon) pvalue_onq, lons_cyclic = shiftgrid(180., pvalue_onq, lons_cyclic, start=False) m.drawmapboundary(fill_color='white', color='dimgray', linewidth=0.7) m.drawcoastlines(color='dimgray', linewidth=0.8) parallels = np.arange(-90, 90, 45) meridians = np.arange(-180, 180, 60) #m.drawparallels(parallels,labels=[True,True,True,True], # linewidth=0.6,color='dimgray',fontsize=6) #m.drawmeridians(meridians,labels=[True,True,True,True], # linewidth=0.6,color='dimgray',fontsize=6)
# irrotational (divergent) wind components, gradients of absolute vorticity. eta = w.absolutevorticity() div = w.divergence() uchi, vchi = w.irrotationalcomponent() etax, etay = w.gradient(eta) # Combine the components to form the Rossby wave source term. S = eta * -1. * div - uchi * etax + vchi * etay # Pick out the field for December at 200 hPa. time_constraint = iris.Constraint(month='Dec') level_constraint = iris.Constraint(Level=[200]) add_month(S, 'time') S_200 = S.extract(time_constraint & level_constraint) # Plot Rossby wave source. m = Basemap(projection='cyl', resolution='c', llcrnrlon=0, llcrnrlat=-90, urcrnrlon=360.01, urcrnrlat=90) lons, lats = S_200.coord('longitude'), S_200.coord('latitude') S_200, lonsc = addcyclic(S_200.data, lons.points) x, y = m(*np.meshgrid(lonsc, lats.points)) clevs = [-30, -25, -20, -15, -10, -5, 0, 5, 10, 15, 20, 25, 30] m.contourf(x, y, S_200*1e11, clevs, cmap=plt.cm.RdBu_r, extend='both') m.drawcoastlines() m.drawparallels((-90, -60, -30, 0, 30, 60, 90), labels=[1,0,0,0]) m.drawmeridians((0, 60, 120, 180, 240, 300, 360), labels=[0,0,0,1]) plt.colorbar(orientation='horizontal') plt.title('Rossby Wave Source ($10^{-11}$s$^{-1}$)', fontsize=16) plt.show()
def mapdap( varname = 'hr24_prcp', bbox = '-180,-90,180,90', url = 'http://opendap.bom.gov.au:8080/thredds/dodsC/PASAP/atmos_latest.nc', timeindex = 'Default', imgwidth = 256, imgheight = 256, request = 'GetMap', time = 'Default', save_local_img = False, colorrange = (-4,4), palette = 'RdYlGn', colorbounds = 'Default', style = 'grid', ncolors = 10, mask = -999, plot_mask = True, mask_varname = 'mask', mask_value = 1.0 ): """ Using Basemap, create a contour plot using some dap available data Data is assumed to have dimensions [time,lat,lon] TODO -- deal with other shapes TODO -- determine the dimension ordering using CF convention varname -- name of variable in opendap file bbox -- lonmin,latmin,lonmax,latmax for plot url -- OPEnDAP url timeindex -- time index to plot imgwidth,imgheight -- size of png image to return request -- 'GetMap','GetLegend','GetFullFigure' time -- time vale to plot. Assumes a particular format."%Y-%m-%dT%H:%M:%S" mask -- mask out these values if plot_mask is True, mask_varname and mask_value must be given """ transparent = True lonmin,latmin,lonmax,latmax = tuple([float(a) for a in bbox.rsplit(',')]) # It's not clear there is any point in this. Pydap doesn't actually # download data until you subscript if url not in cache: dset = open_url(url) else: dset = cache[url] # Get the correct time. time_var = dset['time'] time_units = time_var.attributes['units'] available_times = np.array(time_var[:]) # TODO there is a potential conflict here between time and timeindex. # On the one hand we want to allow using the actual time value. # On the other hand we want to make it easy to get a time index # without knowing the value. timestep=0 if timeindex == 'Default': timestep=0 else: timestep=int(timeindex) if time != 'Default': dtime = datetime.datetime.strptime(time, "%Y-%m-%dT%H:%M:%S" ) reftime = date2num(dtime,time_units) timestep = np.where(available_times >= reftime)[0].min() # TODO Get only the section of the field we need to plot # TODO Determine lat/lon box indices and only download this slice # TODO Set default range (the below does not work) #colorrange = np.min(var),np.max(var) lat = dset['lat'][:] lon = dset['lon'][:] # CHANGED var = dset[varname][timestep,:,:] #xcoords = lonmin,lonmax #xcoords,lon,var = transform_lons(xcoords,lon,var) # TODO # Needs mre thought - the idea here is to only grab a slice of the data # Need to grab a slightly larger slice of data so that tiling works. #lat_idx = (lat > latmin) & (lat < latmax) #lon_idx = (lon > lonmin) & (lon < lonmax) #lat = dset['lat'][lat_idx] #lon = dset['lon'][lon_idx] #latdx1 = np.where(lat_idx)[0].min() #latdx2 = np.where(lat_idx)[0].max() #londx1 = np.where(lon_idx)[0].min() #londx2 = np.where(lon_idx)[0].max() #var = var[latdx1:latdx2+1,londx1:londx2+1] #var = dset[varname][timestep,latdx1:latdx2+1,londx1:londx2+1] # todo clean up this logic if 'mask' in dset.keys(): if plot_mask: maskvar = dset['mask'][timestep,:,:] #maskvar = dset['mask'][timestep,latdx1:latdx2+1,londx1:londx2+1] varm = np.ma.masked_array(var,mask=maskvar) mask = varm.mask else: varm = np.ma.masked_array(var,mask=np.isinf(var)) xcoords = lonmin,lonmax # Call the trans_coords function to ensure that basemap is asked to # plot something sensible. xcoords,lon,varm = transform_lons(xcoords,lon,varm) lonmin,lonmax = xcoords varnc = dset[varname] try: var_units = varnc.attributes['units'] except KeyError: var_units = '' # Plot the data # For the basemap drawing we can't go outside the range of coordinates # WMS requires us to give an empty (transparent) image for these spurious lats # uc = upper corner, lc = lower corner bmapuclon=lonmax bmaplclon=lonmin bmapuclat=min(90,latmax) bmaplclat=max(-90,latmin) if bmaplclat==90: bmaplclat = 89.0 if bmapuclat==-90: bmapuclat = -89.0 # TODO set figsize etc here fig = mpl.figure.Figure() canvas = FigureCanvas(fig) ax = fig.add_axes((0,0,1,1),frameon=False,axisbg='k',alpha=0,visible=False) m = Basemap(projection='cyl',resolution='c',urcrnrlon=bmapuclon, urcrnrlat=bmapuclat,llcrnrlon=bmaplclon,llcrnrlat=bmaplclat, suppress_ticks=True,fix_aspect=False,ax=ax) DPI=100.0 # Convert the latitude extents to Basemap coordinates bmaplatmin,bmaplonmin = m(latmin,lonmin) bmaplatmax,bmaplonmax = m(latmax,lonmax) lon_offset1 = abs(bmaplclon - bmaplonmin) lat_offset1 = abs(bmaplclat - bmaplatmin) lon_offset2 = abs(bmapuclon - bmaplonmax) lat_offset2 = abs(bmapuclat - bmaplatmax) lon_normstart = lon_offset1 / abs(bmaplonmax - bmaplonmin) lat_normstart = lat_offset1 / abs(bmaplatmax - bmaplatmin) ax_xfrac = abs(bmapuclon - bmaplclon)/abs(bmaplonmax - bmaplonmin) ax_yfrac = abs(bmapuclat - bmaplclat)/abs(bmaplatmax - bmaplatmin) # Set plot_coords, the plot boundaries. If this is a regular WMS request, # the plot must fill the figure, with whitespace for invalid regions. # If it's a full figure, we need to make sure there is space for the legend # and also for the text. if request == 'GetFullFigure': coords = lonmin,latmin,lonmax,latmax plot_coords = figurePlotDims(imgheight,imgwidth,coords) else: plot_coords = (lon_normstart,lat_normstart,ax_xfrac,ax_yfrac) m = Basemap(projection='cyl',resolution='c',urcrnrlon=bmapuclon, urcrnrlat=bmapuclat,llcrnrlon=bmaplclon,llcrnrlat=bmaplclat, suppress_ticks=True,fix_aspect=False,ax=ax) ax = fig.add_axes(plot_coords,frameon=False,axisbg='k') m.ax = ax varm,lonwrap = addcyclic(varm,lon) x,y = m(*np.meshgrid(lonwrap[:],lat[:])) """ To plot custom colors rgb_cmap = mpl.colors.ListedColormap([ (0.0,0.0,0.0), (0.25,0.25,0.25), (0.3,0.25,0.25), (0.5,0.5,0.5), (0.6,0.5,0.5), (0.75,0.75,0.75), (0.75,0.85,0.75), (1.0,1.0,1.0) ],name='rgbcm') default_color_bounds = [-1,-0.75,-0.5,-0.25,0.0,0.25,0.5,0.75,1.0] default_norm = mpl.colors.BoundaryNorm(default_color_bounds, rgb_cmap.N) m.contourf(x,y,var,cmap=rgb_cmap,norm=default_norm) contours = m.contour(x,y,var,cmap=rgb_cmap,norm=default_norm) contours.clabel(colors='k') """ colormap = mpl.cm.get_cmap(palette) # colormap = cmap_discretize(colormap,ncolors) # if colorbounds = 'Default': # colorbounds = list(np.arange(colorrange[0],colorrange[1]+increment,increment)) # else: # colorbounds = list(np.arange(colorrange[0],colorrange[1]+increment,increment)) # Do some checks on the size of the list, and fix if we can # pass if style == 'contour': # Interpolate to a finer resolution # TODO: make this sensitive to the chosen domain increment = float(colorrange[1]-colorrange[0]) / float(ncolors-2) colorbounds = list(np.arange(colorrange[0],colorrange[1]+increment,increment)) # CHANGED colormap = cmap_discretize(colormap,ncolors) colvs =[-999]+colorbounds+[999] lat_idx = np.argsort(lat) lat = lat[lat_idx] varm = varm[lat_idx,:] data_lonmin = min(lonwrap) data_lonmax = max(lonwrap) data_latmin = min(lat) data_latmax = max(lat) new_lons = np.arange(data_lonmin-1.0,data_lonmax+1.0,1.0) new_lats = np.arange(data_latmin-1.0,data_latmax+1.0,1.0) newx,newy = m(*np.meshgrid(new_lons[:],new_lats[:])) x = newx y = newy # Two pass interpolation to deal with the mask. # The first pass does a bilinear, the next pass does a nearest neighbour to keep the mask # These steps slow down the plotting significantly # It's not clear this is working, and the problem is likely solved by # ensuring the right mask is used! varm_bl = interp(varm, lonwrap[:], lat[:], newx, newy,order=1) varm_nn = interp(varm, lonwrap[:], lat[:], newx, newy,order=0) varm = varm_bl varm[varm_nn.mask == 1] = varm_nn[varm_nn.mask == 1] # contourf has an extent keyword (x0,x1,y0,y1) # return "mapdap\n" # STUCK it gets stuck here (in apache) main_render = m.contourf(x,y,varm[:,:],colorbounds,extend='both',cmap=colormap,ax=ax) contours = m.contour(x,y,varm,colorbounds,colors='k',ax=ax) contours.clabel(colors='k',rightside_up=True,fmt='%1.1f',inline=True) elif style == 'grid': main_render = m.pcolormesh(x,y,varm[:,:],vmin=colorrange[0],vmax=colorrange[1], cmap=colormap,ax=ax) elif style == 'grid_threshold': increment = float(colorrange[1]-colorrange[0]) / float(ncolors) colorbounds = list(np.arange(colorrange[0],colorrange[1]+increment,increment)) colornorm = mpl.colors.BoundaryNorm(colorbounds,colormap.N) main_render = m.pcolor(x,y,varm[:,:],vmin=colorrange[0],vmax=colorrange[1], cmap=colormap,ax=ax,norm=colornorm) else: main_render = m.pcolormesh(x,y,varm[:,:],vmin=colorrange[0],vmax=colorrange[1], cmap=colormap,ax=ax) fig.set_dpi(DPI) fig.set_size_inches(imgwidth/DPI,imgheight/DPI) title_font_size = 9 tick_font_size = 8 if request == 'GetFullFigure': # Default - draw 5 meridians and 5 parallels n_merid = 5 n_para = 5 # base depends on zoom mint = (lonmax - lonmin)/float(n_merid) base = mint meridians = [lonmin + i*mint for i in range(n_merid)] meridians = [ int(base * round( merid / base)) for merid in meridians] # Some sensible defaults for debugging #meridians = [45,90,135,180,-135,-90,-45] pint = int((latmax - latmin)/float(n_para)) base = pint parallels = [latmin + i*pint for i in range(1,n_para+1)] parallels = [ int(base * round( para / base)) for para in parallels] #parallels = [-60,-40,-20,0,20,40,60] #parallels = [((parallel + 180.) % 360.) - 180. for parallel in parallels] m.drawcoastlines(ax=ax) m.drawmeridians(meridians,labels=[0,1,0,1],fmt='%3.1f',fontsize=tick_font_size) m.drawparallels(parallels,labels=[1,0,0,0],fmt='%3.1f',fontsize=tick_font_size) m.drawparallels([0],linewidth=1,dashes=[1,0],labels=[0,1,1,1],fontsize=tick_font_size) titlex,titley = (0.05,0.98) # CHANGED # STUCK getting an error somewhere in this function # title = get_pasap_plot_title(dset,varname=varname,timestep=timestep) title = "We're getting errors in the get title function" fig.text(titlex,titley,title,va='top',fontsize=title_font_size) colorbar_font_size = 8 if request == 'GetLegendGraphic': # Currently we make the plot, and then if the legend is asked for # we use the plot as the basis for the legend. This is not optimal. # Instead we should be making the legend manually. However we need # to set up more variables, and ensure there is a sensible min and max. # See the plot_custom_colors code above fig = mpl.figure.Figure(figsize=(64/DPI,256/DPI)) canvas = FigureCanvas(fig) # make some axes cax = fig.add_axes([0,0.1,0.2,0.8],axisbg='k') # put a legend in the axes cbar = fig.colorbar(main_render,cax=cax,extend='both',format='%1.1f') cbar.set_label(var_units,fontsize=colorbar_font_size) for t in cbar.ax.get_yticklabels(): t.set_fontsize(colorbar_font_size) # i.e. you don't need to plot the figure... #fig.colorbar(filled_contours,cax=cax,norm=colornorm,boundaries=colvs,values=colvs, # ticks=colorbounds,spacing='proportional') elif request == 'GetFullFigure': # Add the legend to the figure itself. # Figure layout parameters # plot_coords = tuple with (xi,yi,dx,dy) # legend_coords = tuple with (xi,yi,dx,dy) as per mpl convention # First change the plot coordinates so that they do not cover the whole image legend_coords = (0.8,0.1,0.02,plot_coords[3]) cax = fig.add_axes(legend_coords,axisbg='k') cbar = fig.colorbar(main_render,cax=cax,extend='both') for t in cbar.ax.get_yticklabels(): t.set_fontsize(colorbar_font_size) cbar.set_label(var_units,fontsize=colorbar_font_size) transparent=False # Experimenting here with custom color map and ticks. Assigning everything manually # (e.g. ticks=[-2,-1,0,1,2]) is easy. Doing it in an automated way given a range is # hard... #fig.colorbar(filled_contours,cax=cax,boundaries=colvs,ticks=colorbounds) #,norm=colornorm,#boundaries=colvs,values=colvs, #extend='both') imgdata = StringIO.StringIO() fig.savefig(imgdata,format='png',transparent=transparent) if save_local_img: fig.savefig('map_plot_wms_output.png',format='png') return if url not in cache: cache[url] = dset value = imgdata.getvalue() #imgdata.close() fig = None return value
def transform_lons(coords,lon,f): """ Take bounding box longitudes and transform them so that basemap plots sensibly. """ """ Arguments coords -- a tuple compose of lonmin,lonmax lon -- numpy array of longitudes f -- numpy array of the field being plotted >>> trans_coords() This logic can probably be simplified as it was built incrementally to solve several display issues. See tests/allplots.shtml for the tests that drove this function. """ x1,x2 = coords lont = lon # To handle 360 degree plots if x2 == x1: x2 = x1 + 360 # Basemap doesn't always play well with negative longitudes so convert to 0-360 lon2360 = lambda x: ((x + 360.) % 360.) if x2 < 0: x2 = lon2360(x2) x1 = lon2360(x1) lont = lon2360(lont) # If this has resulted in xmin greater than xmax, need to reorder if x2 < x1: x2 = x2 + 360 # If the start lon is less than zero, then convert to -180:180 # It's not clear this will ever be executed, given the above code if (x1 < 0) or (x2 == x1 and x2 == 180): x1 = ((x1 + 180.) % 360.) - 180. x2 = ((x2 + 180.) % 360.) - 180. lont = ((lont + 180.) % 360.) - 180. # If this has resulted in xmin greater than xmax, we need to reorder if x2 < x1: x2 = x2 + 360 # If the x2 range is greater than 360 (plots that span both dl and pm) # then remap the longitudes to this range if x2 > 360: idx = lont < x1 lont[idx] = lont[idx] + 360 # Remap the longitudes for this case too if x1 < 0 and x2 > 180: idx = lont < x1 lont[idx] = lont[idx] + 360 # The special case of 0-360 if x2 == x1: if x2 == 0: x1 = 0 x2 = 360 else: x2 = abs(x2) x1 = -x2 coords = x1,x2 # Ensure lons are ascending, and shuffle the field with the same indices idx = np.argsort(lont) lont = lont[idx] ft = f[:,idx] ft, lont = addcyclic(ft,lont) return coords,lont,ft
m = Basemap( projection = 'cyl', \ resolution = 'c' , \ llcrnrlon = b.lon_min, \ llcrnrlat = b.lat_min, \ urcrnrlon = b.lon_max, \ urcrnrlat = b.lat_max, \ suppress_ticks = True, \ fix_aspect = False, \ ax = ax) # From ContourPlot lats = dset.get_lats() data = dset.get_data() data,lonwrap = addcyclic(dset.get_data(), dset.get_lons()) increment = float(crange[1] - crange[0]) / float(ncolors-2) cbounds = list(np.arange(crange[0],crange[1] + increment, increment )) colvs = [-999]+cbounds+[999] # Sort latitudes and data lat_idx = np.argsort(lats) lats = lats[lat_idx] data = data[lat_idx] data_lon_min = min(lonwrap) data_lon_max = max(lonwrap) data_lat_min = min(lats) data_lat_max = max(lats)
def unpack_data_object(data_object, x_variable, y_variable, x_wrap_start): """ :param data_object A cube or an UngriddedData object :return: A dictionary containing x, y and data as numpy arrays """ from iris.cube import Cube import iris.plot as iplt import iris import logging from mpl_toolkits.basemap import addcyclic no_of_dims = len(data_object.shape) data = data_object.data # ndarray x = get_coord(data_object, x_variable, data) if hasattr(x, 'points'): x = x.points try: coord = data_object.coord(name=x_variable) x_axis_name = guess_coord_axis(coord) except CoordinateNotFoundError: x_axis_name = None y = get_coord(data_object, y_variable, data) if hasattr(y, 'points'): y = y.points # Must use special function to check equality of array here, so NaNs are returned as equal and False is returned if # arrays have a different shape if array_equal_including_nan(y, data) or array_equal_including_nan(y, x): y = None if array_equal_including_nan(x, data): data = y y = None if isinstance(data_object, Cube): plot_defn = iplt._get_plot_defn(data_object, iris.coords.POINT_MODE, ndims=no_of_dims) if plot_defn.transpose: data = data.T x = x.T y = y.T # Check for auxiliary coordinates. aux_coords = False for coord in data_object[0].coords(dim_coords=False): aux_coords = True if no_of_dims == 2: # If we have found some auxiliary coordinates in the data and the shape of x data or y data is the same as # data assume we have a hybrid coordinate (which is two dimensional b nature. Perhaps need a more robust # method for detecting this. if aux_coords and (data.shape == x.shape or data.shape == y.shape): # Work out which set of data needs expanding to match the coordinates of the others. Note there can only # ever be one hybrid coordinate axis. if y.shape == data.shape: if y[:, 0].shape == x.shape: x, _y = np.meshgrid(x, y[0, :]) elif y[0, :].shape == x.shape: x, _y = np.meshgrid(x, y[:, 0]) elif x.shape == data.shape: if x[:, 0].shape == y.shape: y, _x = np.meshgrid(y, x[0, :]) elif x[0, :].shape == y.shape: y, _x = np.meshgrid(y, x[:, 0]) else: try: data, x = addcyclic(data, x) x, y = np.meshgrid(x, y) except: data, y = addcyclic(data, y) y, x = np.meshgrid(y, x) if x_axis_name == 'X' and x_wrap_start is not None: # x = iris.analysis.cartography.wrap_lons(x, x_wrap_start, 360) if isnan(x_wrap_start): raise InvalidCommandLineOptionError('Overall range for longitude axis must be within 0 - 360 degrees.') x = fix_longitude_range(x, x_wrap_start) logging.debug("Shape of x: " + str(x.shape)) if y is not None: logging.debug("Shape of y: " + str(y.shape)) logging.debug("Shape of data: " + str(data.shape)) return {"data": data, "x": x, "y": y}
(5./12.)*ddivdtspec[:,nold] ) phispec += dt*( \ (23./12.)*dphidtspec[:,nnew] - (16./12.)*dphidtspec[:,nnow]+ \ (5./12.)*dphidtspec[:,nold] ) # implicit hyperdiffusion for vort and div. vrtspec *= hyperdiff_fact divspec *= hyperdiff_fact # switch indices, do next time step. nsav1 = nnew; nsav2 = nnow nnew = nold; nnow = nsav1; nold = nsav2 time2 = time.clock() print 'CPU time = ',time2-time1 # make a orthographic plot of potential vorticity. m = Basemap(projection='ortho',lat_0=45,lon_0=0) # dimensionless PV pvg = (0.5*hbar*grav/omega)*(vrtg+f)/phig print 'max/min PV',pvg.min(), pvg.max() lons1d = (180./np.pi)*x.lons; lats1d = (180./np.pi)*x.lats pvg,lons1d = addcyclic(pvg,lons1d) lons, lats = np.meshgrid(lons1d,lats1d) x,y = m(lons,lats) levs = np.arange(-0.2,1.801,0.1) m.drawmeridians(np.arange(-180,180,60)) m.drawparallels(np.arange(-80,81,20)) CS=m.contourf(x,y,pvg,levs,cmap=plt.cm.spectral,extend='both') m.colorbar() plt.title('PV (T%s with hyperdiffusion, hour %6.2f)' % (ntrunc,t/3600.)) plt.show()
# read lats,lons. lats = data.variables['lat'][:] lons1 = data.variables['lon'][:] nlats = len(lats) nlons = len(lons1) # read prmsl, convert to hPa (mb). prmsl = 0.01 * data.variables['prmslmsl'][0] # the window parameter controls the number of highs and lows detected. # (higher value, fewer highs and lows) local_min, local_max = extrema(prmsl, mode='wrap', window=50) # create Basemap instance. m =\ Basemap(llcrnrlon=0,llcrnrlat=-80,urcrnrlon=360,urcrnrlat=80,projection='mill') # add wrap-around point in longitude. prmsl, lons = addcyclic(prmsl, lons1) # contour levels clevs = np.arange(900, 1100., 5.) # find x,y of map projection grid. lons, lats = np.meshgrid(lons, lats) x, y = m(lons, lats) # create figure. fig = plt.figure(figsize=(8, 4.5)) ax = fig.add_axes([0.05, 0.05, 0.9, 0.85]) cs = m.contour(x, y, prmsl, clevs, colors='k', linewidths=1.) m.drawcoastlines(linewidth=1.25) m.fillcontinents(color='0.8') m.drawparallels(np.arange(-80, 81, 20), labels=[1, 1, 0, 0]) m.drawmeridians(np.arange(0, 360, 60), labels=[0, 0, 0, 1]) xlows = x[local_min] xhighs = x[local_max]
lats, uwnd, vwnd = order_latdim(lats, uwnd, vwnd) # Create a VectorWind instance to handle the computation of streamfunction and # velocity potential. w = VectorWind(uwnd, vwnd) # Compute the streamfunction and velocity potential. Also use the bundled # tools to re-shape the outputs to the 4D shape of the wind components as they # were read off files. sf, vp = w.sfvp() sf = recover_data(sf, uwnd_info) vp = recover_data(vp, uwnd_info) # Pick out the field for December at 200 hPa and add a cyclic point (the # cyclic point is for plotting purposes). sf_200, lons_c = addcyclic(sf[11, 9], lons) vp_200, lons_c = addcyclic(vp[11, 9], lons) # Plot streamfunction. m = Basemap(projection='cyl', resolution='c', llcrnrlon=0, llcrnrlat=-90, urcrnrlon=360.01, urcrnrlat=90) x, y = m(*np.meshgrid(lons_c, lats)) clevs = [-120, -100, -80, -60, -40, -20, 0, 20, 40, 60, 80, 100, 120] m.contourf(x, y, sf_200*1e-06, clevs, cmap=plt.cm.RdBu_r, extend='both') m.drawcoastlines() m.drawparallels((-90, -60, -30, 0, 30, 60, 90), labels=[1,0,0,0]) m.drawmeridians((0, 60, 120, 180, 240, 300, 360), labels=[0,0,0,1]) plt.colorbar(orientation='horizontal') plt.title('Streamfunction ($10^6$m$^2$s$^{-1}$)', fontsize=16)
barlimq = [np.round(np.arange(0,0.6,0.1),2)] datasetsq = [r'SHUFFLE'] colorbarendq = ['max'] cmapq = [cm.classic_16.mpl_colormap] ax1 = plt.axes([.24,.54,.4,.25]) m = Basemap(projection='moll',lon_0=0,resolution='l',area_thresh=10000) circle = m.drawmapboundary(fill_color='dimgrey') circle.set_clip_on(False) m.drawcoastlines(color='darkgrey',linewidth=0.35) ### Colorbar limits barlim = barlimq[0] var, lons_cyclic = addcyclic(mean, lon1) var, lons_cyclic = shiftgrid(180., var, lons_cyclic, start=False) lon2d, lat2d = np.meshgrid(lons_cyclic, lat1) x, y = m(lon2d, lat2d) ### Make the plot continuous cs = m.contourf(x,y,var,limitsq[0], extend=colorbarendq[0]) cs.set_cmap(cmapq[0]) ax1.annotate(r'\textbf{%s}' % (datasetsq[0]),xy=(0,0),xytext=(0.865,0.91), textcoords='axes fraction',color='dimgrey',fontsize=9, rotation=332,ha='center',va='center') cbar = m.colorbar(cs,drawedges=False,location='bottom',extendfrac=0.07, extend=colorbarendq[0],pad=0.1)
# Compute components of rossby wave source: absolute vorticity, divergence, # irrotational (divergent) wind components, gradients of absolute vorticity. eta = w.absolutevorticity() div = w.divergence() uchi, vchi = w.irrotationalcomponent() etax, etay = w.gradient(eta) # Combine the components to form the Rossby wave source term. Re-shape the # Rossby wave source array to the 4D shape of the wind components as they were # read off files. S = -eta * div - uchi * etax + vchi * etay S = recover_data(S, uwnd_info) # Pick out the field for December at 200 hPa and add a cyclic point (the # cyclic point is for plotting purposes). S_200, lons_c = addcyclic(S[11, 9], lons) # Plot Rossby wave source. m = Basemap(projection='cyl', resolution='c', llcrnrlon=0, llcrnrlat=-90, urcrnrlon=360.01, urcrnrlat=90) x, y = m(*np.meshgrid(lons_c, lats)) clevs = [-30, -25, -20, -15, -10, -5, 0, 5, 10, 15, 20, 25, 30] m.contourf(x, y, S_200*1e11, clevs, cmap=plt.cm.RdBu_r, extend='both') m.drawcoastlines() m.drawparallels((-90, -60, -30, 0, 30, 60, 90), labels=[1,0,0,0]) m.drawmeridians((0, 60, 120, 180, 240, 300, 360), labels=[0,0,0,1]) plt.colorbar(orientation='horizontal') plt.title('Rossby Wave Source ($10^{-11}$s$^{-1}$)', fontsize=16) plt.show()
# Compute components of rossby wave source: absolute vorticity, divergence, # irrotational (divergent) wind components, gradients of absolute vorticity. eta = w.absolutevorticity() div = w.divergence() uchi, vchi = w.irrotationalcomponent() etax, etay = w.gradient(eta) # Combine the components to form the Rossby wave source term. Re-shape the # Rossby wave source array to the 4D shape of the wind components as they were # read off files. S = -eta * div - (uchi * etax + vchi * etay) S = recover_data(S, uwnd_info) # Pick out the field for December and add a cyclic point (the cyclic point is # for plotting purposes). S_dec, lons_c = addcyclic(S[11], lons) # Plot Rossby wave source. m = Basemap(projection='cyl', resolution='c', llcrnrlon=0, llcrnrlat=-90, urcrnrlon=360.01, urcrnrlat=90) x, y = m(*np.meshgrid(lons_c, lats)) clevs = [-30, -25, -20, -15, -10, -5, 0, 5, 10, 15, 20, 25, 30] m.contourf(x, y, S_dec * 1e11, clevs, cmap=plt.cm.RdBu_r, extend='both') m.drawcoastlines() m.drawparallels((-90, -60, -30, 0, 30, 60, 90), labels=[1, 0, 0, 0]) m.drawmeridians((0, 60, 120, 180, 240, 300, 360), labels=[0, 0, 0, 1]) plt.colorbar(orientation='horizontal')
print verifdates lats = latitudes[:] nlats = len(lats) lons1 = longitudes[:] nlons = len(lons1) # unpack 2-meter temp forecast data. t2mvar = data.variables['tmp2m'] t2min = t2mvar[0:ntimes,:,:] t2m = np.zeros((ntimes,nlats,nlons+1),t2min.dtype) # create Basemap instance for Orthographic projection. m = Basemap(lon_0=-90,lat_0=60,projection='ortho') # add wrap-around point in longitude. for nt in range(ntimes): t2m[nt,:,:], lons = addcyclic(t2min[nt,:,:], lons1) # convert to celsius. t2m = t2m-273.15 # contour levels clevs = np.arange(-30,30.1,2.) lons, lats = np.meshgrid(lons, lats) x, y = m(lons, lats) # create figure. fig=plt.figure(figsize=(6,8)) # make subplots. for nt,fcsthr in enumerate(fcsthrs): ax = fig.add_subplot(321+nt) cs = m.contourf(x,y,t2m[nt,:,:],clevs,cmap=plt.cm.jet,extend='both') m.drawcoastlines(linewidth=0.5) m.drawcountries() m.drawparallels(np.arange(-80,81,20))
print verifdates lats = latitudes[:] nlats = len(lats) lons1 = longitudes[:] nlons = len(lons1) # unpack 2-meter temp forecast data. t2mvar = data.variables['tmp2m'] t2min = t2mvar[0:ntimes, :, :] t2m = np.zeros((ntimes, nlats, nlons + 1), t2min.dtype) # create Basemap instance for Orthographic projection. m = Basemap(lon_0=-90, lat_0=60, projection='ortho') # add wrap-around point in longitude. for nt in range(ntimes): t2m[nt, :, :], lons = addcyclic(t2min[nt, :, :], lons1) # convert to celsius. t2m = t2m - 273.15 # contour levels clevs = np.arange(-30, 30.1, 2.) lons, lats = np.meshgrid(lons, lats) x, y = m(lons, lats) # create figure. fig = plt.figure(figsize=(6, 8)) # make subplots. for nt, fcsthr in enumerate(fcsthrs): ax = fig.add_subplot(321 + nt) cs = m.contourf(x, y, t2m[nt, :, :], clevs, cmap=plt.cm.jet, extend='both') m.drawcoastlines(linewidth=0.5) m.drawcountries() m.drawparallels(np.arange(-80, 81, 20))
grid = AxesGrid(fig, [0.05,0.01,0.9,0.9], nrows_ncols=(3, 2), axes_pad=0.25, cbar_mode='single', cbar_pad=0.3, cbar_size=0.1, cbar_location='top', share_all=True, ) # create Basemap instance for Orthographic projection. m = Basemap(lon_0=-90,lat_0=60,projection='ortho') # add wrap-around point in longitude. t2m = np.zeros((ntimes,nlats,nlons+1),np.float32) for nt in range(ntimes): t2m[nt,:,:], lons = addcyclic(t2mvar[nt,:,:], lons1) # convert to celsius. t2m = t2m-273.15 # contour levels clevs = np.arange(-30,30.1,2.) lons, lats = np.meshgrid(lons, lats) x, y = m(lons, lats) # make subplots. for nt,fcsthr in enumerate(fcsthrs): ax = grid[nt] m.ax = ax cs = m.contourf(x,y,t2m[nt,:,:],clevs,cmap=plt.cm.jet,extend='both') m.drawcoastlines(linewidth=0.5) m.drawcountries() m.drawparallels(np.arange(-80,81,20)) m.drawmeridians(np.arange(0,360,20))
limit = np.arange(-0.2, 0.21, 0.02) barlim = np.arange(-0.2, 0.3, 0.2) lonq, latq = np.meshgrid(lon, lat) fig = plt.figure() for i in range(len(var)): ax1 = plt.subplot(1, 6, i + 1) m = Basemap(projection='ortho', lon_0=0, lat_0=89, resolution='l', area_thresh=10000.) varn, lons_cyclic = addcyclic(var[i], lon) varn, lons_cyclic = shiftgrid(180., varn, lons_cyclic, start=False) lon2d, lat2d = np.meshgrid(lons_cyclic, lat) x, y = m(lon2d, lat2d) pvarn, lons_cyclic = addcyclic(pvar[i], lon) pvarn, lons_cyclic = shiftgrid(180., pvarn, lons_cyclic, start=False) climoq, lons_cyclic = addcyclic(climos[i], lon) climoq, lons_cyclic = shiftgrid(180., climoq, lons_cyclic, start=False) circle = m.drawmapboundary(fill_color='white', color='dimgrey', linewidth=0.7) circle.set_clip_on(False) if varnames[v] == 'RNET':
lats, uwnd, vwnd = order_latdim(lats, uwnd, vwnd) # Create a VectorWind instance to handle the computation of streamfunction and # velocity potential. w = VectorWind(uwnd, vwnd) # Compute the streamfunction and velocity potential. Also use the bundled # tools to re-shape the outputs to the 4D shape of the wind components as they # were read off files. sf, vp = w.sfvp() sf = recover_data(sf, uwnd_info) vp = recover_data(vp, uwnd_info) # Pick out the field for December and add a cyclic point (the cyclic point is # for plotting purposes). sf_dec, lons_c = addcyclic(sf[11], lons) vp_dec, lons_c = addcyclic(vp[11], lons) # Plot streamfunction. m = Basemap(projection='cyl', resolution='c', llcrnrlon=0, llcrnrlat=-90, urcrnrlon=360.01, urcrnrlat=90) x, y = m(*np.meshgrid(lons_c, lats)) clevs = [-120, -100, -80, -60, -40, -20, 0, 20, 40, 60, 80, 100, 120] m.contourf(x, y, sf_dec*1e-06, clevs, cmap=plt.cm.RdBu_r, extend='both') m.drawcoastlines() m.drawparallels((-90, -60, -30, 0, 30, 60, 90), labels=[1,0,0,0]) m.drawmeridians((0, 60, 120, 180, 240, 300, 360), labels=[0,0,0,1]) plt.colorbar(orientation='horizontal') plt.title('Streamfunction ($10^6$m$^2$s$^{-1}$)', fontsize=16)
# map = Basemap(llcrnrlon=120.,llcrnrlat=-60.,urcrnrlon=180.,urcrnrlat=-30., rsphere=(6378137.00,6356752.3142), resolution='l',projection='lcc', lat_0=-20.,lon_0=180.,lat_ts=-50.) # # map = Basemap(llcrnrlon=90.,llcrnrlat=-60.,urcrnrlon=180.,urcrnrlat=-20., rsphere=(6378137.00,6356752.3142), resolution='l',projection='lcc', lat_0=-20.,lon_0=180.,lat_ts=-50.) # map.drawparallels(np.arange(-90,-10,10),labels=[0,1,0,0]) #left, right, top or bottom of the plot. # map.drawmeridians(np.arange(-180,180,10),labels=[0,0,0,1]) map = Basemap(projection='cyl',llcrnrlon=130,llcrnrlat=-70,urcrnrlon=180,urcrnrlat=-30,resolution='l') # plot (unwarped) rgba image. im = map.bluemarble(scale=0.5) map.drawcoastlines(linewidth=0.5,color='0.5') map.drawmeridians(np.arange(-180,180,10),labels=[0,0,0,1],color='0.5') map.drawparallels(np.arange(-90,90,10),labels=[1,0,0,0],color='0.5') local_min, local_max = extrema(prmsl, mode='wrap', window=50) prmsl, lons = addcyclic(prmsl, lons1) clevs = np.arange(900,1100.,5) lons, lats = np.meshgrid(lons, lats) x, y = map(lons, lats) cs = map.contour(x,y,prmsl,clevs,colors='w',linewidths=1.) map.drawcoastlines(linewidth=1.25) #map.fillcontinents(color='0.8') #map.etopo() map.bluemarble() #map.shadedrelief() xlows = x[local_min]; xhighs = x[local_max] ylows = y[local_min]; yhighs = y[local_max] lowvals = prmsl[local_min]; highvals = prmsl[local_max]
# calculate the difference, absolute and percentage gpp_dif = gpp_sitch - gpp_ctr gpp_dif_per = gpp_dif / gpp_ctr gpp = gpp_dif_per * 100 # Plot of global temperature on our random day fig = plt.figure() fig.subplots_adjust(left=0., right=1., bottom=0., top=0.9) # Mercator projection m = Basemap(projection='merc', llcrnrlat=-60, urcrnrlat=60,\ llcrnrlon=-180, urcrnrlon=180, resolution='c', lon_0=0) m.drawcoastlines() m.drawmapboundary() # Make the plot continuous gpp_cyclic, lons_cyclic = addcyclic(gpp[ :, :], lons) # Shift the grid so lons go from -180 to 180 instead of 0 to 360. gpp_cyclic, lons_cyclic = shiftgrid(180., gpp_cyclic, lons_cyclic, start=False) # Create 2D lat/lon arrays for Basemap lon2d, lat2d = np.meshgrid(lons_cyclic, lats) # Transforms lat/lon into plotting coordinates for projection x, y = m(lon2d, lat2d) # Plot of gpp with 11 contour intervals levels = [-40,-35,-30,-25,-20,-15,-10,-5,0] #cs = m.contourf(x, y, gpp_cyclic, 11, cmap=plt.cm.Spectral_r) cmap = plt.cm.get_cmap("hot") cs = m.contourf(x, y, gpp_cyclic, levels, cmap=cmap) cbar = plt.colorbar(cs, orientation='horizontal', shrink=0.5) cbar.set_label("percentage (%)") plt.title("GPP difference") plt.show()