m.drawmapboundary(fill_color='white',color='dimgrey',linewidth=0.7) cs = m.contourf(x,y,var,limit,extend='both') cs1 = m.contourf(x,y,pvar,colors='None',hatches=['....']) if varnames[v] == 'Z30': # the interval is 250 m cs2 = m.contour(x,y,climoq,np.arange(21900,23500,250), colors='k',linewidths=1.5,zorder=10) if varnames[v] == 'RNET': m.drawcoastlines(color='darkgray',linewidth=0.3) m.fillcontinents(color='dimgrey') else: m.drawcoastlines(color='dimgray',linewidth=0.8) if varnames[v] == 'T2M': cmap = ncm.cmap('NCV_blu_red') cs.set_cmap(cmap) elif varnames[v] == 'Z500': cmap = ncm.cmap('nrl_sirkes') cs.set_cmap(cmap) elif varnames[v] == 'Z30': cmap = ncm.cmap('nrl_sirkes') cs.set_cmap(cmap) elif varnames[v] == 'SLP': cmap = ncm.cmap('nrl_sirkes') cs.set_cmap(cmap) elif varnames[v] == 'U10' or varnames[v] == 'U300': cmap = ncm.cmap('temp_diff_18lev') cs.set_cmap(cmap) cs.set_cmap(cmap) elif varnames[v] == 'SWE':
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) m.drawmapboundary(fill_color='white', color='dimgrey', linewidth=0.7) cs = m.contourf(x, y, var, limit, extend='max', norm=norm) cs1 = m.contourf(x, y, pvar, colors='None', hatches=['....']) m.drawcoastlines(color='dimgrey', linewidth=0.6) if varnamesn[v] == 'T2M': cmap = ncm.cmap('NCV_blu_red') cs.set_cmap(cmap) elif varnamesn[v] == 'T925': cmap = ncm.cmap('NCV_blu_red') cs.set_cmap(cmap) elif varnamesn[v] == 'T850': cmap = ncm.cmap('NCV_blu_red') cs.set_cmap(cmap) ### Add experiment text to subplot if any([v == 0, v == 2, v == 4]): ax.annotate(r'\textbf{%s}' % varnamesn[v], xy=(0, 0), xytext=(-0.14, 0.5), textcoords='axes fraction', color='k',
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 cs2 = m.contour(x,y,climoq,np.arange(21900,23500,250), colors='k',linewidths=1.5,zorder=10) m.drawcoastlines(color='dimgray',linewidth=0.8) if varnames[v] == 'T2M': cmap = ncm.cmap('NCV_blu_red') cs.set_cmap(cmap) elif varnames[v] == 'SLP': cmap = cmocean.cm.balance cs.set_cmap(cmap) elif varnames[v] == 'Z500': cmap = cmocean.cm.balance cs.set_cmap(cmap) elif varnames[v] == 'Z30': cmap = cmocean.cm.balance cs.set_cmap(cmap) elif varnames[v] == 'U10' or varnames[v] == 'U300' or varnames[v] == 'U500': cmap = ncm.cmap('NCV_blu_red') cs.set_cmap(cmap) elif varnames[v] == 'SWE': cmap = cmap = cmocean.cm.balance
ax.spines['bottom'].set_color('dimgrey') ax.spines['left'].set_linewidth(2) ax.spines['bottom'].set_linewidth(2) ax.tick_params('both', length=4, width=2, which='major', color='dimgrey') if r < 2: ax.spines['bottom'].set_color('w') ax.tick_params('x', length=0, width=0, which='major', color='w') plt.plot([0] * len(corrvar[r]), linewidth=2, color='dimgrey', linestyle='--') color = iter( ncm.cmap('MPL_gnuplot2')(np.linspace(0, 0.8, len(corrvar[r])))) for i in range(len(corrvar[r])): c = next(color) plt.plot(corrvar[r][i], linewidth=1.5, color=c, alpha=1, label=r'\textbf{%s}' % varnames[i], linestyle='-', marker='o', markersize=3) if r == 1: plt.ylabel(r'\textbf{Pattern Correlation [R]}', color='dimgrey', fontsize=13)
plt.gca().invert_yaxis() plt.yscale('log', nonposy='clip') plt.ylabel(r'\textbf{Pressure (hPa)}', color='dimgrey', fontsize=15, labelpad=1) xlabels = [r'Sep', r'Oct', r'Nov', r'Dec', r'Jan', r'Feb', r'Mar', r'Apr'] plt.xticks(np.arange(0, 212, 30), xlabels, fontsize=8) plt.yticks(zscale, map(str, zscale), ha='right', fontsize=8) plt.minorticks_off() plt.xlim([30, 210]) plt.ylim([1000, 10]) cmap = ncm.cmap('temp_diff_18lev') cs.set_cmap(cmap) cbar_ax = fig.add_axes([0.312, 0.1, 0.4, 0.03]) cbar = fig.colorbar(cs, cax=cbar_ax, orientation='horizontal', extend='max', extendfrac=0.07, drawedges=False) cbar.outline.set_edgecolor('dimgrey') cbar.set_label(r'\textbf{m/s}', fontsize=11, color='dimgray') cbar.set_ticks(barlim) cbar.set_ticklabels(list(map(str, barlim))) cbar.ax.tick_params(axis='x', size=.01)
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) t1 = plt.annotate(r'\textbf{GRAPHIC}: Zachary Labe (@ZLabe)', textcoords='axes fraction', xy=(0, 0), xytext=(0.02, -0.167), fontsize=4.5, color='w',
anomalies = slp - meanslp yr = np.where(years == 2012)[0][0] springanom = np.nanmean(anomalies[:, 3:6, :, :], axis=1) summeranom = np.nanmean(anomalies[:, 6:9, :, :], axis=1) ### Plot figure plt.rc('text', usetex=True) plt.rc('font', **{'family': 'sans-serif', 'sans-serif': ['Avant Garde']}) fig = plt.figure() barlim = np.arange(-10, 12, 2) values = np.arange(-10, 10.1, 0.5) cmap = ncm.cmap('testcmap') ax1 = plt.subplot(611) plt.contourf(anomalies[yr, 3, :, :], values, cmap=cmap, extend='both') ax1.spines['top'].set_color('darkgrey') ax1.spines['right'].set_color('darkgrey') ax1.spines['bottom'].set_color('darkgrey') ax1.spines['left'].set_color('darkgrey') plt.setp(ax1.get_yticklabels(), visible=False) plt.setp(ax1.get_xticklabels(), visible=False) ax1.xaxis.set_tick_params(size=0) ax1.yaxis.set_tick_params(size=0) plt.grid(color='darkgrey') ax1.yaxis.grid(False)
parallels = np.arange(50, 86, 5) meridians = np.arange(-180, 180, 30) m.drawparallels(parallels, labels=[False, False, False, False], linewidth=0.0, color='w') par = m.drawmeridians(meridians, labels=[True, True, False, False], linewidth=0.0, fontsize=4, color='w') setcolor(par, 'darkgrey') ### Set colormap cmap2 = cmocean.cm.balance cmap2 = ncm.cmap('BlRe') cs2.set_cmap(cmap2) cbar = m.colorbar(cs2, drawedges=False, location='bottom', pad=0.14, size=0.1) ticks = np.arange(0, 8, 1) cbar.set_ticks(barlim) cbar.set_ticklabels(list(map(str, barlim))) cbar.set_label( r'\textbf{SEA SURFACE TEMPERATURE ANOMALIES [\textbf{$\bf{^\circ}$C}]}', fontsize=14, color='w') cbar.ax.tick_params(axis='x', size=.0001)
for t in x[m][1]: t.set_color(color) m.drawparallels(parallels, labels=[False, False, False, False], linewidth=0.2, fontsize=4) mer = m.drawmeridians(meridians, labels=[False, False, True, True], linewidth=0.2, fontsize=4) setcolor(mer, 'k') values = np.arange(-1, 1.1, 0.1) cs = m.contourf(x, y, var, values, extend='both') cmap = ncm.cmap('BrownBlue12') cs.set_cmap(cmap) cbar = plt.colorbar(cs, orientation='horizontal', extend='both', extendfrac=0.06, pad=0.05, drawedges=True) cbar.set_ticks(np.arange(-1, 2, 1)) cbar.set_ticklabels(map(str, np.arange(-1, 2, 1))) cbar.set_label(r'\textbf{Difference (m)}', fontsize=8, color='k', labelpad=1) cbar.ax.tick_params(labelsize=8) plt.savefig(directoryfigure + 'seasonalcycle_lens.png', dpi=300)
#m = Basemap(projection='robin',lon_0=0,resolution='l') m = Basemap(projection='ortho',lon_0=300,lat_0=-25,resolution='l') var = sit[9] - sit2[9] m.drawmapboundary(fill_color='white') m.drawcoastlines(color='dimgrey',linewidth=0.3) parallels = np.arange(-90,90,30) meridians = np.arange(-180,180,60) m.drawparallels(parallels,labels=[True,True,True,True], linewidth=0.3,color='k',fontsize=6) m.drawmeridians(meridians,labels=[True,True,True,True], linewidth=0.3,color='k',fontsize=6) m.drawlsmask(land_color='darkgrey',ocean_color='mintcream') cs = m.contourf(lons,lats,var,80,latlon=True,extend='both') cs1 = m.contour(lons,lats,var,50,linewidths=0.2,colors='darkgrey', linestyles='-',latlon=True) cmap = ncm.cmap('GMT_ocean') cs.set_cmap(cmap) cbar = plt.colorbar(cs,extend='both') #cbar.set_label(r'\textbf{SIT}') #ticks = np.arange(0,8,1) #cbar.set_ticks(ticks) #cbar.set_ticklabels(map(str,ticks)) plt.savefig(directoryfigure + 'testss_sstf.png',dpi=300) print 'Completed: Script done!'
style = 'polar' if style == 'ortho': m = Basemap(projection='ortho',lon_0=-90, lat_0=70,resolution='l',round=True) elif style == 'polar': m = Basemap(projection='npstere',boundinglat=56,lon_0=270, resolution='l',round =True) m.drawmapboundary(fill_color='darkgrey',linewidth=0.7) m.drawcoastlines(color='darkgrey',linewidth=0.2) m.drawlsmask(land_color='dimgrey',ocean_color='mintcream') #### Plot filled contours x,y = m(x1,y1) diff[np.isnan(diff)]=0.0 csm=plt.get_cmap(ncm.cmap('NCV_blu_red'),16) norm = c.BoundaryNorm(np.arange(-4,4.5,0.5),csm.N) cs = m.hexbin(x,y,C=diff,vmin = -4,vmax = 4,cmap=csm,norm=norm) barlim = np.arange(-4,5,1) m.fillcontinents(color='dimgrey') ax.annotate(r'\textbf{%s}' % yearsq[i],xy=(0,0),xytext=(0.865,0.90), textcoords='axes fraction',color='k',fontsize=11, rotation=320,ha='center',va='center') cbar_ax = fig.add_axes([0.313,0.12,0.4,0.03]) cbar = fig.colorbar(cs,cax=cbar_ax,orientation='horizontal', extend='both',extendfrac=0.07,drawedges=False) cbar.set_ticks(barlim) cbar.set_ticklabels(list(map(str,barlim)))
cs1 = m.contourf(x, y, pvalue_onq, colors='None', hatches=['....'], linewidths=0.4) ax1.annotate(r'\textbf{ON}', xy=(0, 0), xytext=(0.35, 1.05), xycoords='axes fraction', fontsize=25, color='dimgrey', rotation=0) cmap = ncm.cmap('precip4_diff_19lev') cs.set_cmap(cmap) ########################################################################### ax2 = plt.subplot(132) m = Basemap(projection='ortho', lon_0=0, lat_0=89, resolution='l', area_thresh=10000.) var, lons_cyclic = addcyclic(diff_dj, lon) var, lons_cyclic = shiftgrid(180., var, lons_cyclic, start=False) lon2d, lat2d = np.meshgrid(lons_cyclic, lat)
def make_animation(fig, frames, outputname): ani = animation.FuncAnimation(fig, animate, frames, interval=0.01, blit=False, init_func=initial, repeat=False) # ani.save(outputname, writer=animation.FFMpegWriter(fps=4)) ani.save(outputname, writer='imagemagick') plt.close(fig) return ani ######################################### Run the Code ############# a = xr.open_dataset('sst_anom_mhws.nc') a1 = a.sel(time=slice('2010-06-26', '2010-07-29')) import nclcmaps cmap1 = nclcmaps.cmap('sunshine_9lev') ds = a1 * 1 varname = 'sstanom' cartopy_projection = ccrs.Orthographic(central_latitude=0.0, central_longitude=75.0) min_value = 0.00 max_value = 0.8 N = 11 cmap1 = cmap1 fig, ax = make_figure(cartopy_projection) make_animation(fig, frames=ds.time.size, outputname='output.gif')
new_lon = np.linspace(lon[0], lon[-1], len(lon) * new_res, endpoint=True) new_lat = np.linspace(lat[0], lat[-1], len(lat) * new_res, endpoint=True) dset_30_days.load() new_lon, new_lat, matm = regrid(dset_30_days.sum('time')['trmm'].data, lon, lat, new_lon, new_lat) lons, lats = np.meshgrid(new_lon, new_lat) sys.path.append(os.path.join(os.environ['HOME'], 'pythonlibs')) import nclcmaps as ncm cmap = ncm.cmap('GMT_drywet') proj = ccrs.PlateCarree() f, ax = plt.subplots(figsize=(10, 8), subplot_kw=dict(projection=proj)) ax.set_extent([domain['lonmin'], domain['lonmax'], domain['latmin'], domain['latmax']]) ax.add_feature(cfeature.GSHHSFeature(scale='full', levels=[1,2,3,4])) im = ax.contourf(lons, lats, matm, levels=np.arange(0, round_down(matm.max(), 20), 20), cmap=cmap, extend='max', transform=proj) c = ax.contour(lons, lats, matm, levels=np.arange(0, round_down(matm.max(), 20), 20), color='k', linewidths=0.5, transform=proj) cb = plt.colorbar(im, shrink=0.8)
x, y = prj(lons, lats) ll_lon, ll_lat = prj(min(x), min(y), inverse=True) ur_lon, ur_lat = prj(max(x), max(y), inverse=True) return Basemap(projection='stere', lat_0=lat_0, lon_0=lon_0, llcrnrlon=ll_lon, llcrnrlat=ll_lat, urcrnrlon=ur_lon, urcrnrlat=ur_lat, round=True, resolution='l') m = polar_stere(lonmin,lonmax,latmin,latmax) m.drawcoastlines(color = 'r',linewidth=1.4) m.drawmapboundary(color='k') m.drawlsmask(land_color='k',ocean_color='k') cs = m.contourf(lon,lat,ice[:,:],np.arange(20,100.01,1),extend='min',latlon=True) cmap = ncm.cmap('MPL_YlGnBu') cmap = cmocean.cm.ice cs.set_cmap(cmap) m.fillcontinents(color='k') cbar = m.colorbar(cs,location='right',pad = 0.2) cbar.outline.set_edgecolor('k') barlim = np.arange(20,101,10) cbar.set_ticks(barlim) cbar.set_ticklabels(list(map(str,barlim))) cbar.set_label(r'\textbf{Concentration (\%)}',fontsize=13, alpha=0.6) cbar.ax.tick_params(axis='y', size=.01) fig.suptitle(r'\textbf{ARCTIC SEA ICE -- %s}' % titletime,
m4.drawmapboundary(fill_color='white',color='dimgray',linewidth=0.7) m4.drawmapboundary(fill_color='white',color='dimgray',linewidth=0.7) m4.drawcoastlines(color='darkgrey',linewidth=0.1) parallels = np.arange(-90,90,30) meridians = np.arange(-180,180,60) #m.drawparallels(parallels,labels=[True,True,True,True], # linewidth=0.1,color='k',fontsize=6) #m.drawmeridians(meridians,labels=[True,True,True,True], # linewidth=0.1,color='k',fontsize=6) #m4.drawlsmask(land_color='dimgray',ocean_color='mintcream') cs = m4.contourf(x,y,var,limdiff,extend='both') cs1 = m4.contour(x,y,var,barlimdiff,linewidths=0.1,colors='darkgrey', linestyles='-') cmap = ncm.cmap('amwg_blueyellowred') cs.set_cmap(cmap) cbar = m4.colorbar(cs,location='bottom',pad = 0.2,extend='max', drawedges=False) ticks = barlimdiff labels = list(map(str,barlimdiff)) cbar.set_ticks(ticks) cbar.set_ticklabels(labels) cbar.set_label(r'\textbf{Difference [m]}',fontsize=11,color='dimgray') cbar.ax.tick_params(axis='x', size=.01) m4.fillcontinents(color='dimgray') plt.annotate(r'\textbf{HIT}',xy=(-0.82,1.1), xycoords='axes fraction',color='dimgray',fontsize=30,alpha=1) plt.annotate(r'\textbf{CIT--HIT}',xy=(0.2,1.1),
varns[:] = var ncfile.close() print '*Completed: Created netCDF4 File!' sncn = regrid(lat1,lon1,lat2,lon2,snc,years) netcdfPiomas(lat2,lon2,sncn,directorydata1) ### Plot figure plt.rc('text',usetex=True) plt.rc('font',**{'family':'sans-serif','sans-serif':['Avant Garde']}) fig = plt.figure() ax = plt.subplot(111) cmap = ncm.cmap('MPL_PuRd') sncn[np.where(sncn==0.0)] = np.nan var = sncn[-2,3,:,:]*100. m = Basemap(projection='npstere',boundinglat=66,lon_0=270, resolution='l',round =True) m.drawmapboundary(fill_color='white') m.drawcoastlines(color='k',linewidth=0.3) parallels = np.arange(50,90,10) meridians = np.arange(-180,180,30) m.drawparallels(parallels,labels=[False,False,False,False], linewidth=0.3,color='k',fontsize=6) m.drawmeridians(meridians,labels=[True,True,False,False], linewidth=0.3,color='k',fontsize=6)
ncfile.close() print('*Completed: Created netCDF4 File!') sicn = regrid(lat1, lon1, lat2, lon2, sic, years) netcdfPiomas(lat2, lon2, sicn, directorydata1) ### Plot figure plt.rc('text', usetex=True) plt.rc('font', **{'family': 'sans-serif', 'sans-serif': ['Avant Garde']}) fig = plt.figure() ax = plt.subplot(111) cmap = ncm.cmap('MPL_cubehelix') sicn[np.where(sicn == 0.0)] = np.nan var = sicn[-2, 3, :, :] m = Basemap(projection='npstere', boundinglat=55, lon_0=270, resolution='l', round=True) m.drawmapboundary(fill_color='white') m.drawcoastlines(color='k', linewidth=0.3) parallels = np.arange(50, 90, 10) meridians = np.arange(-180, 180, 30) m.drawparallels(parallels,
def hov_diagram(lon, y, contour_data, levels, col="testcmap", ax=None, rng=None, step=60, ew=False, norm=False, extend='both', vmin=None, vmax=None): """Draw hovmoller diagrams (time vs lat) Inputs: lon, y = x and y axes respectively. lon is usually longitude, y is time, contour_data = data to be plotted (lon x time) levels = levels for the contour of the hovmoller diagram [optional] ax = an axis on a plot to draw the plot on extend = Which side of the colorbar to extend: Must be one of 'both', 'min', 'max', 'neither' ew = Add "E" or "W" tag to longitude axis col = ncl colormap. By default test cmap rng = minimum axis tick and maximum x axis tick (an array of 2 values) defaults to None and choose the min and max of the longitudes passed step = steps taken on longitde axis""" l1 = np.min(lon) l2 = np.max(lon) if (extend not in ['both', 'min', 'max', 'neither']): raise ValueError("hov_diagram: Unexpected value for extend") X, Y = np.meshgrid(lon, y) if (isinstance(col, str)): cmap = ncm.cmap(col) if (ax is not None): CS = ax.contourf(X, Y, contour_data, levels, cmap=cmap, extend=extend) else: CS = plt.contourf(X, Y, contour_data, levels, cmap=cmap, extend=extend) else: if (ax is not None): CS = ax.contourf(X, Y, contour_data, levels, colors=col, extend=extend) else: CS = plt.contourf(X, Y, contour_data, levels, colors=col, extend=extend) if (ax is None): ax = plt.gca() ax.minorticks_on() ax.tick_params(axis="both", which="both", direction="out") ax.tick_params(axis="y", which="minor", left="off") ax.tick_params(axis="both", which="both", top="off", right="off") if (rng is None): tck = np.arange(l1, l2, step) else: if (len(rng) == 2): tck = np.arange(rng[0], rng[1], step) else: raise ValueError("Expected only a 2 value array for rng") if (ew): tck_lb = [str(np.int(np.abs(t))) + __get_EW__(t) for t in tck] else: tck_lb = [str(t) for t in tck] ax.set_xticks(tck) ax.set_xticklabels(tck_lb, fontsize=7) return CS
anomalies = h7 - meanh7 yr = np.where(years == 2011)[0][0] springanom = np.nanmean(anomalies[:, 3:6, :, :], axis=1) summeranom = np.nanmean(anomalies[:, 6:9, :, :], axis=1) ### Plot figure plt.rc('text', usetex=True) plt.rc('font', **{'family': 'sans-serif', 'sans-serif': ['Avant Garde']}) fig = plt.figure() values = np.arange(-100, 101, 5) barlim = np.arange(-100, 101, 50) cmap = ncm.cmap('BlueDarkRed18') ax1 = plt.subplot(611) plt.contourf(anomalies[yr, 3, :, :], values, cmap=cmap, extend='both') ax1.spines['top'].set_color('darkgrey') ax1.spines['right'].set_color('darkgrey') ax1.spines['bottom'].set_color('darkgrey') ax1.spines['left'].set_color('darkgrey') plt.setp(ax1.get_yticklabels(), visible=False) plt.setp(ax1.get_xticklabels(), visible=False) ax1.xaxis.set_tick_params(size=0) ax1.yaxis.set_tick_params(size=0) plt.grid(color='darkgrey') ax1.yaxis.grid(False)
def plot_contour_map(contour_data, lats, lons, minlev, maxlev, levspace, add_cyclic=False, lat_lim=[-90, 90], lon_lim=[0, 360], proj="cyl", drawgrids=None, gridfont=10, gridlat=[-90, 90], gridlon=[0, 360], center_lon=0, drawls=False, cmap="testcmap", ax=None, extend='both', conf=None, ms=0.1, rs=3, scatter=True): """Plot a contour map on a basemap imported from mpl_toolkits contour_data - Data for contour map should be lat x lon lats - latitude values lons - longitude values minlev - minimum contour level maxlev - maximum contour level levspace - spacing between contours extend [optional] - Takes 4 values 'min', 'max', 'both', 'neither'. Used for the contour map. 'both' by default add_cyclic [optional] - Add a cyclic point to the plot. Useful for full longitude ranges proj [optional] - Projection of the map. Takes only three possible values from the range of projections available in matplotlib ['hammer', 'robin', 'cyl']. Rectangle region bounds are ignored for both hammer and robin. Only lat_0 is considered. Default is 'cyl' drawgrids [optional] - Draw grids on the map at this spacing - a 2 element tuple. Is only used for non-cylindrical maps. Default None gridfont [optional] - Fontsize of grid label lat_lim [optional] - Limits for latitude [0, 360] by default. Must be a 2 value array-like lon_lim [optional] - Limits for longitude [-90,90] by default. Must be a 2 value array-like lonshift [optional] - Shift the longitude to match lon_0. This argument takes the amount by which to shift drawls [Optional] - Toggles Landsea masks. Set to False by default cmap[Optional] - ncl colormap to use. Default is testcmap, or a matplotlib map or a list of colors ax [Optional] - which axis to draw upon conf [Optional] - Draw a scatter plot of 1s and 0s signifiying confidence levels""" if (len(lat_lim) != 2) or (len(lon_lim) != 2): raise ValueError("Only 2 values expected for axis limits") # Data for the contour map clevs = np.arange(minlev, maxlev + levspace / 2., levspace) if (proj not in ('cyl', 'hammer', 'robin')): raise ValueError( "plot_contour_map: proj not in one of ['robin', 'hammer', cyl'") if (proj == 'cyl'): m = Basemap(projection = 'cyl', llcrnrlat = lat_lim[0], \ urcrnrlat = lat_lim[1], \ area_thresh = 10000, llcrnrlon = lon_lim[0], # urcrnrlon = 360, urcrnrlon = lon_lim[1], resolution = 'l', suppress_ticks = False, ax = ax) elif (proj == 'hammer' or proj == 'robin'): m = Basemap(projection=proj, area_thresh=10000, lon_0=center_lon, resolution='l', suppress_ticks=True, ax=ax) m.drawcoastlines() nlon = len(lons) # If lsmask is required if (drawls): m.drawlsmask() if (proj != 'cyl'): # If central longitude is not zero or the central value of the longitude array, the longitude grid # also has to be shifted to accomodate for the new grid structure if ( lons[nlon / 2] != center_lon ): # which means we need to ensure central longitude is set to lat_0 lon_start = center_lon - 180 contour_data, lons = shiftgrid(lon_start, contour_data, lons) # Addcyclic is applied after centering the logitude since it can break the code because of the monotonicity issue if (add_cyclic): contour_data, lons = addcyclic(contour_data, lons) x, y = np.meshgrid(lons, lats) x, y = m(x, y) # Project meshgrid onto map if (drawgrids is not None): if (len(drawgrids) != 2): raise ValueError( "plot_contour_map: Expected 2 values as tuple for drawgrids" ) m.drawparallels(np.arange(gridlat[0], gridlat[1] + 1, drawgrids[0]), labels=[1, 0, 0, 0], fontsize=gridfont) m.drawmeridians(np.arange(gridlon[0], gridlon[1] + 1, drawgrids[1]), fontsize=gridfont) else: if (add_cyclic): contour_data, lons = addcyclic(contour_data, lons) x, y = np.meshgrid(lons, lats) # contour_data = contour_data[:,lon_pos] if (extend not in ['both', 'min', 'max', 'neither']): raise ValueError( "plot_contour_map: extend only takes 3 values - ['both', 'min', 'max']" ) if (isinstance(cmap, str)): cmap = ncm.cmap(cmap) if (isinstance(cmap, str) or isinstance(cmap, mcl.ListedColormap) or isinstance(cmap, mcl.LinearSegmentedColormap)): cs = m.contourf(x, y, contour_data, clevs, cmap=cmap, extend=extend) elif (isinstance(cmap, np.ndarray)): cs = m.contourf(x, y, contour_data, clevs, colors=cmap, extend=extend) else: raise ValueError("Invalid Colormap provided") # Hack for map limits. Note: there needs to be a better way or simply migrate to cartopy if (proj != 'cyl'): # Map projections for latitude llcrnrlon, llcrnrlat = m(min(lons), lat_lim[0]) urcrnrlon, urcrnrlat = m(max(lons), lat_lim[1]) if (ax is None): ax = plt.gca() ax.set_ylim(llcrnrlat, urcrnrlat) # Drawing map boundary with black background. # Relies on resolution being a little off. Is an unavoidable hack. Need to find something better m.drawmapboundary(fill_color='k') # Hatching the plot with significance levels if (conf is not None): conf[~conf.mask] = ms if (scatter): m.scatter(x[::rs, ::rs], y[::rs, ::rs], conf[::rs, ::rs], marker='.', color='k', edgecolor=None, lw=0) else: m.contourf(x, y, conf, n_levels=2, hatches=[None, '\\\+///'], colors='none', extend='lower', linecolor='grey') return m, cs
var, limit, extend='both', alpha=0.7, antiliased=True) cs1 = m.contourf(x, y, pvar, colors='None', hatches=['....']) cs2 = m.contour(lon2c, lat2c, climo, np.arange(-200, 201, 60), colors='k', linewidths=1.5, latlon=True, zorder=10) cmap = ncm.cmap('nrl_sirkes') cs.set_cmap(cmap) m.drawcoastlines(color='dimgray', linewidth=0.8) ### Add experiment text to subplot ax1.annotate(r'%s' % experiments[i], xy=(0, 0), xytext=(0.865, 0.90), textcoords='axes fraction', color='k', fontsize=11, rotation=320, ha='center', va='center')
# Make the plot continuous barlim = np.arange(-5, 5.1, 2) 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 = m.contourf(x, y, var[:, :], np.arange(-5, 5.1, 0.25), extend='both') cs1 = m.contour(x, y, var[:, :], np.arange(-5, 5.1, 0.25), linewidths=0.2, colors='k', linestyles='-') cmap = ncm.cmap('BlueWhiteOrangeRed') cs.set_cmap(cmap) cbar = m.colorbar(cs, location='right', pad='10%', drawedges=True) cbar.set_ticks(barlim) cbar.set_ticklabels(map(str, barlim)) cbar.ax.tick_params(axis='x', size=.1) cbar.set_label(r'\textbf{degrees C}') fig.suptitle(r'\textbf{925T anomalies - %s %s-%s}' % (months, year1, year2)) plt.savefig(directoryfigure + 'TAS/tas_%s_%s%s.png' % (months, year1, year2), dpi=300) 'Completed: Script done!'
cs2 = plt.contour(lat,lev,climovar,np.arange(-20,101,5), linewidths=0.6,colors='dimgrey') plt.contourf(latq,levq,pvar,colors='None',hatches=['////'], linewidth=5) plt.gca().invert_yaxis() plt.yscale('log',nonposy='clip') plt.xlim([0,90]) plt.ylim([1000,10]) plt.xticks(np.arange(0,96,15),map(str,np.arange(0,91,15)),fontsize=8) plt.yticks(zscale,map(str,zscale),ha='right',fontsize=8) plt.minorticks_off() if varnames[v] == 'U': cmap = ncm.cmap('NCV_blu_red') cs.set_cmap(cmap) elif varnames[v] == 'TEMP': cmap = ncm.cmap('NCV_blu_red') cs.set_cmap(cmap) elif varnames[v] == 'GEOP': cmap = cmocean.cm.balance cs.set_cmap(cmap) elif varnames[v] == 'V': cmap = ncm.cmap('temp_diff_18lev') cs.set_cmap(cmap) elif varnames[v] == 'EGR': cmap = cmocean.cm.curl cs.set_cmap(cmap) ### Add experiment text to subplot
m.drawlsmask(land_color='darkgrey',ocean_color='mintcream') ### Adjust maximum limits values = np.arange(-3,3.1,0.25) ### Plot filled contours cs = m.contourf(x,y,var, values,extend='both') cs1 = m.contour(x,y,var, values,linewidths=0.2,colors='darkgrey', linestyles='-') cs2 = ax.scatter(x,y,varscat,color='k',marker='.',alpha=0.5, edgecolor='k',linewidth=0.2) ### Set colormap cmap = ncm.cmap('temp_19lev') cs.set_cmap(cmap) cbar_ax = fig.add_axes([0.313,0.13,0.4,0.03]) cbar = fig.colorbar(cs,cax=cbar_ax,orientation='horizontal', extend='both',extendfrac=0.07,drawedges=True) cbar.set_ticks(np.arange(-3,4,1)) cbar.set_ticklabels(map(str,np.arange(-3,4,1))) cbar.set_label(r'\textbf{Difference (meters)}') plt.subplots_adjust(wspace=-0.28) plt.subplots_adjust(hspace=0.15) plt.subplots_adjust(bottom=0.2) plt.subplots_adjust(top=0.87)