def plot_topBL(self,datagrid,ugrid,vgrid,filename): module = (np.sqrt(ugrid*ugrid+vgrid*vgrid))*3.6 fig = plt.figure(figsize=(figsize,figsize),dpi=self.cfg.map_dpi) Lon,Lat = np.meshgrid(self.lon, self.lat) map = Basemap(llcrnrlon=self.BB['lon'][0],llcrnrlat=self.BB['lat'][0],urcrnrlon=self.BB['lon'][1],urcrnrlat=self.BB['lat'][1], rsphere=(6378137.00,6356752.3142), resolution='l',projection='merc') x, y = map(Lon, Lat) cs2 = map.contourf(x,y,datagrid,512) levels = np.arange(0, 5000, 100) CS = map.contour(x,y,datagrid, levels, linewidths=0.01,colors = 'k') plt.clabel(CS,inline=1,fmt='%d') lw = 1 + 4*module/50 map.streamplot(x,y,ugrid,vgrid, density=3, color='k', linewidth=lw , arrowsize=2 ) for ix in np.arange(0,module.shape[1],2): for iy in np.arange(0,module.shape[0],2): #print ix,iy ilon = self.lon[ix] ilat = self.lat[iy] a,b = map(ilon, ilat) plt.text(a,b ,int(module[iy,ix]),fontsize=fontsize,fontweight='bold', ha='center',va='center',color='r') plt.subplots_adjust(left=0.0, right=figsize, top=figsize, bottom=0.0) self.saveplot(plt,filename) plt.close() # Legend fig1 = plt.figure(figsize=(11,11),dpi=100) cb = map.colorbar(cs2,"bottom", size="5%", pad="100%") name = filename + '_legend.jpg' plt.savefig("maps/"+name, dpi=100,bbox_inches='tight',transparent=False) plt.close() list_of_maps_to_send.append("maps/"+name) img1 = Image.open("maps/"+name) w, h = img1.size box = (20, h-70, w-10, h-10) area = img1.crop(box) area.save("maps/"+name, 'jpeg') plt.close()
def plot2D_field(self,gridu,gridv,module,direction,filename): fig = plt.figure(figsize=(figsize,figsize),dpi=self.cfg.map_dpi) Lon,Lat = np.meshgrid(self.lon, self.lat) map = Basemap(llcrnrlon=self.BB['lon'][0],llcrnrlat=self.BB['lat'][0],urcrnrlon=self.BB['lon'][1],urcrnrlat=self.BB['lat'][1], rsphere=(6378137.00,6356752.3142), resolution='l',projection='merc') x, y = map(Lon, Lat) cs2 = map.contourf(x,y,module,512) # barbs = map.barbs(x,y,gridu,gridv,length=8,barbcolor='k',flagcolor='r',linewidth=0.5) # barbs = map.quiver(x,y,gridu,gridv,scale=100) # qk = plt.quiverkey(barbs, 0.1, 0.1, 20, '20 m/s', labelpos='W') lw = lw = 1 + 4*module/module.max() map.streamplot(x,y,gridu,gridv, density=3, color='k', linewidth=lw , arrowsize=2 ) plt.subplots_adjust(left=0.0, right=figsize, top=figsize, bottom=0.0) self.saveplot(plt,filename) plt.close() fig1 = plt.figure(figsize=(11,11),dpi=100) cb = map.colorbar(cs2,"bottom", size="5%", pad="100%") name = filename + '_legend.jpg' plt.savefig("maps/"+name, dpi=100,bbox_inches='tight',transparent=False) plt.close() list_of_maps_to_send.append("maps/"+name) img1 = Image.open("maps/"+name) w, h = img1.size box = (20, h-70, w-10, h-10) area = img1.crop(box) area.save("maps/"+name, 'jpeg') plt.close()
def streamplot(field, field2, lons, lats, col): #mp=Basemap(lon_0=0,projection='robin') speed = np.sqrt(field * field + field2 * field2) lw = 5 * speed / speed.max() mp = Basemap(projection='mill',llcrnrlat=-90,urcrnrlat=90,\ llcrnrlon=-180,urcrnrlon=180,resolution='c') fig1 = plt.figure() b, a = np.meshgrid(lons, lats) print b.shape print field.shape b, a = mp(b, a) mp.drawcoastlines() Q = mp.streamplot(b, a, field, field2, color=col, linewidth=lw) plt.show()
lat, rhodot, levels=np.linspace(-colorlevel, colorlevel, 301), vmin=-0.5, vmax=0.5, cmap='CO', latlon=True) #,shading='gourand') plt.colorbar() m.drawcoastlines() m.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=10) m.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=10) #uiv = bx.quiver(xx[::2*iterplevl,::2*iterplevl],yy[::2*iterplevl,::2*iterplevl],uu[::2*iterplevl,::2*iterplevl],vv[::2*iterplevl,::2*iterplevl]) m.streamplot(lon, lat, u, v, linewidth=0.4, density=1.75, latlon=True, color='dimgrey') #(0.74, 0.75, 0.75)) plt.title(strftime("%a, %d %b %Y %H:%M:%S Zulu Time", gmtime(time[t]))) plt.savefig('output2_v2.3.eps', transparent=True, bbox_inches='tight') #uiv = bx.quiver(xx,yy,uu,vv) #dbar = plt.colorbar(geatmap,format=ticker.FuncFormatter(fmt)) #''' ''' ##PLOT DIFFERENT FTLEs #from mpl_toolkits.basemap import Basemap ncfile="windagedata.nc" root = Dataset(ncfile,'r') #read the data vars = root.variables #dictionary, all variables in dataset\ print vars.keys()
lat1 = np.arange(-2, 61, 1) lon1 = np.arange(225, 315, 1) x, y = m(*np.meshgrid(lon1,lat1)) # # cbar = plt.colorbar(cmap='jet',label='meters per second (m/s)',format = "%d") # plt.title('Wind Magnitude\n S2S (1 Degree Resolution)\n') # data1=np.flip(domain11_m, axis=0) # flipping the data for Contour plot rangecontour = np.arange(0, 25, 0.5) cs = m.contourf(x,y,data1,rangecontour, cmap='jet',ax=ax1) u = np.flip(domain11_u, axis=0) v = np.flip(domain11_v, axis=0) # streamline provide the direction understanding of the winds m.streamplot(x, y, u, v, color='w',density=3, linewidth=0.5,arrowsize=1.,ax=ax1) #cmap=plt.cm.coolwarm m.drawparallels(np.arange(-3,60,10),labels=[1,0,0,0],linewidth=0.25,ax=ax1) # draw parallels m.drawmeridians(np.arange(225,315,15),labels=[0,0,0,1],linewidth=0.25,ax=ax1) # draw meridians from mpl_toolkits.axes_grid1 import make_axes_locatable #f.colorbar(cs, orientation="horizontal", ax=axlist) divider = make_axes_locatable(ax1) cax = divider.append_axes("right", size="3%", pad=0.05) plt.colorbar(cs, cax=cax,label='meters per second (m/s)',format = "%d", cmap='jet') plt.savefig(r'C:\Users\Arslaan Khalid\Desktop\S2S\Updated_2019_Analysis\Katrina2005\Figures\true.png',dpi=300, bbox_inches = 'tight', pad_inches = 0.1)
ncfile = NetCDFFile('rita.nc') udat = ncfile.variables['sfc_u'][0,:,:] vdat = ncfile.variables['sfc_v'][0,:,:] lons1 = ncfile.variables['longitude'][:] lats1 = ncfile.variables['latitude'][:] lat0 = lats1[len(lats1)/2]; lon0 = lons1[len(lons1)/2] lons, lats = np.meshgrid(lons1,lats1) ncfile.close() # downsample to finer grid for nicer looking plot. nlats = 2*udat.shape[0]; nlons = 2*udat.shape[1] lons = np.linspace(lons1[0],lons1[-1],nlons) lats = np.linspace(lats1[0],lats1[-1],nlats) lons, lats = np.meshgrid(lons, lats) udat = interp(udat,lons1,lats1,lons,lats) vdat = interp(vdat,lons1,lats1,lons,lats) speed = np.sqrt(udat**2+vdat**2) fig = plt.figure(figsize=(8,8)) m = Basemap(projection='cyl',llcrnrlat=lats1[0],llcrnrlon=lons1[0],urcrnrlat=lats1[-1],urcrnrlon=lons1[-1],resolution='i') x, y = m(lons,lats) m.streamplot(x,y,udat,vdat,color=speed,linewidth=2,density=2,cmap=plt.cm.spectral) m.colorbar() m.drawcoastlines() m.drawmeridians(np.arange(-120,-60,2),labels=[0,0,0,1]) m.drawparallels(np.arange(0,30,2),labels=[1,0,0,0]) plt.title('Hurricane Rita flow field visualized with streamlines',\ fontsize=13) plt.show()
map = Basemap(llcrnrlon=-93.7, llcrnrlat=28., urcrnrlon=-66.1, urcrnrlat=39.5, projection='lcc', lat_1=30., lat_2=60., lat_0=34.83158, lon_0=-98.) ds = gdal.Open("../sample_files/wrf.tiff") lons = ds.GetRasterBand(4).ReadAsArray() lats = ds.GetRasterBand(5).ReadAsArray() u10 = ds.GetRasterBand(1).ReadAsArray() v10 = ds.GetRasterBand(2).ReadAsArray() speed = numpy.sqrt(u10 * u10 + v10 * v10) xx, yy = map.makegrid(v10.shape[1], v10.shape[0], returnxy=True)[2:4] map.streamplot(xx, yy, u10, v10, color=speed, cmap=plt.cm.autumn, linewidth=0.5 * speed) map.drawcoastlines(color='0.15') plt.show()
def plot_flow_vectors_basemap(lons, lats, uu, vv, flow_speed, subregion:list=None, grid_shape=None, ax:Axes=None, streamplot=False, draw_colorbar=True): from mpl_toolkits.basemap import Basemap if grid_shape is None: grid_shape = (300, 300) if subregion is None: subregion = [0, 1, 0, 1] if ax is None: fig = plt.figure() nx, ny = lons.shape b = Basemap(lon_0=180, llcrnrlon=lons[35, 35], llcrnrlat=lats[35, 35], urcrnrlon=lons[nx // 2, ny // 2], urcrnrlat=lats[nx // 2, ny // 2], resolution="i", area_thresh=2000) # im = b.pcolormesh(xx, yy, flow_speed) # b.colorbar(im) stride = 6 uu1, vv1 = b.rotate_vector(uu, vv, lons, lats) lons_g, lats_g, xx_g, yy_g = b.makegrid(*grid_shape, returnxy=True) nx, ny = lons_g.shape i_start, i_end = int(nx * subregion[0]), int(nx * subregion[1]) j_start, j_end = int(ny * subregion[2]), int(ny * subregion[3]) xt, yt, zt = lat_lon.lon_lat_to_cartesian(lons_g.flatten(), lats_g.flatten()) xs, ys, zs = lat_lon.lon_lat_to_cartesian(lons.flatten(), lats.flatten()) ktree = KDTree(data=list(zip(xs, ys, zs))) dists, inds = ktree.query(list(zip(xt, yt, zt))) uu_to_plot = uu1.flatten()[inds].reshape(lons_g.shape) vv_to_plot = vv1.flatten()[inds].reshape(lons_g.shape) flow_speed_to_plot = flow_speed.flatten()[inds].reshape(lons_g.shape) clevs = [0, 0.01, 0.02, 0.04, 0.06, 0.08, 0.12, 0.16] ncolors = len(clevs) - 1 norm = BoundaryNorm(clevs, ncolors) cmap = cm.get_cmap("gist_ncar_r", ncolors) im = b.pcolormesh(xx_g, yy_g, flow_speed_to_plot, alpha=0.5, cmap=cmap, norm=norm) if not streamplot: b.quiver(xx_g[i_start:i_end:stride, j_start:j_end:stride], yy_g[i_start:i_end:stride, j_start:j_end:stride], uu_to_plot[i_start:i_end:stride, j_start:j_end:stride], vv_to_plot[i_start:i_end:stride, j_start:j_end:stride], headlength=2, headaxislength=2, headwidth=4, units="inches", color="k") else: b.streamplot(xx_g, yy_g, uu_to_plot, vv_to_plot, linewidth=0.4, density=3, arrowstyle="fancy", arrowsize=0.4, ax=ax, color="k") # im = b.contourf(xx_g, yy_g, flow_speed_to_plot, levels=clevs, alpha=0.5, cmap=cmap, norm=norm) cb = b.colorbar(im, location="bottom") cb.ax.set_visible(draw_colorbar) b.drawcoastlines(linewidth=0.3, ax=ax) if ax is None: fig.savefig("nemo/circ_annual_mean_basemap.png", bbox_inches="tight", dpi=300) plt.close(fig) return im
lons = np.linspace(lons1[0], lons1[-1], nlons) lats = np.linspace(lats1[0], lats1[-1], nlats) lons, lats = np.meshgrid(lons, lats) udat = interp(udat, lons1, lats1, lons, lats) vdat = interp(vdat, lons1, lats1, lons, lats) speed = np.sqrt(udat**2 + vdat**2) fig = plt.figure(figsize=(8, 8)) m = Basemap(projection='cyl', llcrnrlat=lats1[0], llcrnrlon=lons1[0], urcrnrlat=lats1[-1], urcrnrlon=lons1[-1], resolution='i') x, y = m(lons, lats) m.streamplot(x, y, udat, vdat, color=speed, linewidth=2, density=2, cmap=plt.cm.spectral) m.colorbar() m.drawcoastlines() m.drawmeridians(np.arange(-120, -60, 2), labels=[0, 0, 0, 1]) m.drawparallels(np.arange(0, 30, 2), labels=[1, 0, 0, 0]) plt.title('Hurricane Rita flow field visualized with streamlines',\ fontsize=13) plt.show()
cs = plt.contourf(x, y, speed, bounds, cmap=cmap, extend='both', shading='interp', latlon=True) #map.quiver(x[points], y[points], uwnd[points], vwnd[points],angles='xy',scale=1000,color='k') #map.quiver(x, y, uwnd, vwnd, speed,cmap='rainbow',latlon=True) map.streamplot(x, y, uwnd, vwnd, color='k', cmap='rainbow', density=10, linewidth=2.5, ax=ax) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="2%", pad=0.3) cb = fig.colorbar(cs, cmap=cmap, cax=cax, boundaries=bounds, ticks=np.arange(0, 32, 2), ax=ax) cb.ax.set_yticklabels(['{:.0f}'.format(x) for x in np.arange(0, 32, 2)], fontsize=24,
bounds = np.linspace(1000, 1030, 1000, endpoint=True) cs = plt.contourf(x, y, data, cmap="RdYlBu_r", shading='interp', levels=bounds, extend='both') map.streamplot(x, y, uwnd, vwnd, color='k', density=10., linewidth=2.5, arrowsize=2.5, arrowstyle='->', minlength=0.1, maxlength=5.0) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="2%", pad=0.2) cb = fig.colorbar(cs, cmap="RdYlBu_r", cax=cax, boundaries=bounds, ax=ax, ticks=np.arange(1000, 1031, 5), extend='both')
def basemap(dat, lat, lon, lat_min=None, lat_max=None, lon_min=None, lon_max=None, res='c', proj='mill', origin=0, shift=0, title="", loc=None, loc1=None, loc2=None, lsmask=False, ms_lat=None, ms_lon=None, lms=0.1, ms_length=None, uwinds=None, vwinds=None, hatch=None, hatch_color='none', gc_lat0=None, gc_lon0=None, gc_lat1=None, gc_lon1=None, gc_lat2=None, gc_lon2=None, gdists=None, gc_lw=.5, gc_color=plt.cm.jet, gc_contours=None, gc_extend='both', gc_cbar=False, font_size=8, asp=None, quiverscale=100, stream=None, dat2=None, dat3=None, dat4=None, dat5=None, dat6=None, area1=None, area2=None, area3=None, area4=None, area5=None, area6=None, area7=None, area8=None, area9=None, area10=None, area11=None, area12=None, area13=None, contours=None, contours2=None, contours3=None, contours4=None, contours5=None, contours6=None, lcontours=None, lcd=None, lclabel=None, clim=None, over=None, extend='neither', shaderelief=False, etopo=False, colors=None, colors2=None, colors3=None, colors4=None, colors5=None, colors6=None, color=plt.cm.gist_stern_r, colorbar=True, cbar_title="", hillshade=False, scale=.1, alpha=1, line_color1=None, line_color2=None, line_color3=None, line_color4=None, line_color5=None, line_color6=None, line_color7=None, line_color8=None, line_color9=None, line_color10=None, line_color11=None, line_color12=None, line_color13=None, line_style1='solid', line_style2='solid', line_style3='solid', line_style4='solid', line_style5='solid', line_style6='solid', line_style7='solid', line_style8='solid', line_style9='solid', line_style10='solid', line_style11='solid', line_style12='solid', line_style13='solid', parallels=np.arange(-90., 90., 20.), meridians=np.arange(0., 360., 20.), plabels=[1, 0, 0, 0], mlabels=[0, 0, 0, 1]): """plots a pcolormesh of 2-dim. dat on a geographical grid corresponding to lon and lat, optionally takes fixed colorlimits climl and climr, and saves the figure as title""" if proj == 'mill' or proj == 'cea' or proj == 'cyl': if lat_min is None: m = Basemap(projection=proj, lat_ts=12, llcrnrlon=lon.min() + shift, urcrnrlon=lon.max() + shift, llcrnrlat=lat.min(), urcrnrlat=lat.max(), resolution=res) else: m = Basemap(projection=proj, lat_ts=12, llcrnrlon=lon_min, urcrnrlon=lon_max, llcrnrlat=lat_min, urcrnrlat=lat_max, resolution=res) # m=Basemap(projection = proj, lat_ts=None,llcrnrlon=10, urcrnrlon=190, llcrnrlat=lat.min(), urcrnrlat=lat.max(),resolution = res) # m=Basemap(projection=proj, lat_0 = 0, lon_0 = shift,resolution = 'c') elif proj == 'ortho': m = Basemap(projection='ortho', lat_0=0., lon_0=0., resolution='c') elif proj == 'moll' or proj == 'hammer' or proj == 'robin': m = Basemap(projection=proj, lon_0=shift, resolution='c') elif proj == 'npstere': m = Basemap(projection=proj, lat_0=0., lon_0=0., boundinglat=40, resolution='c') # dat, lons = shiftgrid(0., dat, lon) # print lon lons, dat = m.shiftdata(lon, dat, lon_0=origin + shift) if lcd is not None: lons, lcd = m.shiftdata(lon, lcd, lon_0=origin + shift) # lons = lon # print lons if loc is not None: xloc, yloc = m(loc[0], loc[1]) m.plot(xloc, yloc, marker='D', color='r', markersize=lms) if loc1 is not None: xloc1, yloc1 = m(loc1[0], loc1[1]) m.plot(xloc1, yloc1, marker='D', color='royalblue') if loc2 is not None: xloc2, yloc2 = m(loc2[0], loc2[1]) m.plot(xloc2, yloc2, marker='D', color='darkorange') # dat, lons = addcyclic(dat, lons) if hatch is not None: lons, hatch = m.shiftdata(lon, hatch, lon_0=origin + shift) if area1 is not None: lons, area1 = m.shiftdata(lon, area1, lon_0=origin + shift) if area2 is not None: lons, area2 = m.shiftdata(lon, area2, lon_0=origin + shift) if area3 is not None: lons, area3 = m.shiftdata(lon, area3, lon_0=origin + shift) if area4 is not None: lons, area4 = m.shiftdata(lon, area4, lon_0=origin + shift) if area5 is not None: lons, area5 = m.shiftdata(lon, area5, lon_0=origin + shift) if area6 is not None: lons, area6 = m.shiftdata(lon, area6, lon_0=origin + shift) if area7 is not None: lons, area7 = m.shiftdata(lon, area7, lon_0=origin + shift) if area8 is not None: lons, area8 = m.shiftdata(lon, area8, lon_0=origin + shift) if area9 is not None: lons, area9 = m.shiftdata(lon, area9, lon_0=origin + shift) if area10 is not None: lons, area10 = m.shiftdata(lon, area10, lon_0=origin + shift) if area11 is not None: lons, area11 = m.shiftdata(lon, area11, lon_0=origin + shift) if area12 is not None: lons, area12 = m.shiftdata(lon, area12, lon_0=origin + shift) if area13 is not None: lons, area13 = m.shiftdata(lon, area13, lon_0=origin + shift) # m=Basemap(projection='mill', lat_0 = 0, lon_0 = 160, resolution = 'c') Lon, Lat = np.meshgrid(lons, lat) x, y = m(Lon, Lat) # m.drawcoastlines(linewidth = .3) if lsmask is True: m.drawlsmask(land_color='.1', ocean_color='1.', resolution='h') else: m.drawcoastlines(linewidth=.3) m.drawcountries(linewidth=.3) m.drawmapboundary() # m.readshapefile('/Users/omarlittle/Desktop/Desktop/PIK/climatenetwork/basemap/10m_physical/ne_10m_coastline', 'scale rank', drawbounds=True) # m.drawmapbound) # m.drawcountries(linewidth = .3) m.drawparallels(parallels, labels=plabels, rotation='90', linewidth=.3, fontsize=font_size, family='times new roman') m.drawmeridians(meridians, labels=mlabels, linewidth=.3, fontsize=font_size, family='times new roman') if etopo is True: m.etopo() if shaderelief is True: m.shadedrelief() if hillshade is True: m.warpimage( image= '/Users/omarlittle/Desktop/Desktop/PIK/climatenetwork/basemap/SR_50M.tif', scale=scale) if contours is None: cs = m.pcolormesh(x, y, dat, cmap=color, alpha=alpha) if clim is not None: cs.set_clim(clim) else: if colors is None: cs = m.contourf(x, y, dat, contours, alpha=alpha, cmap=color, extend=extend) else: cs = m.contourf(x, y, dat, contours, alpha=alpha, colors=colors, extend=extend) if contours2 is not None: csa = m.contourf(x, y, dat2, contours2, alpha=alpha, colors=colors2, extend=extend) if contours3 is not None: csb = m.contourf(x, y, dat3, contours3, alpha=alpha, colors=colors3, extend=extend) if contours4 is not None: csc = m.contourf(x, y, dat4, contours4, alpha=alpha, colors=colors4, extend=extend) if contours5 is not None: csd = m.contourf(x, y, dat5, contours5, alpha=alpha, colors=colors5, extend=extend) if contours6 is not None: cse = m.contourf(x, y, dat6, contours6, alpha=alpha, colors=colors6, extend=extend) if hatch is not None: # hat = m.contourf(x, y, hatch, [-2,0, 2], colors = 'none', hatches = [None, '////']) mpl.rcParams['hatch.linewidth'] = 0.1 hat = m.contourf(x, y, hatch, [-2, 0, 2], colors='none', hatches=[None, '///////']) if lcontours is not None: lc = m.contour(x, y, lcd, lcontours, colors='black', linewidths=.2) if lclabel is True: plt.clabel(lc, inline=1, fontsize=8, fmt='%d') if area1 is not None: cs1 = m.contour(x, y, area1, [0], linestyles=line_style1, linewidths=1., colors=line_color1) if area2 is not None: cs2 = m.contour(x, y, area2, [0], linestyles=line_style2, linewidths=1., colors=line_color2) if area3 is not None: cs3 = m.contour(x, y, area3, [0], linestyles=line_style3, linewidths=1., colors=line_color3) if area4 is not None: cs4 = m.contour(x, y, area4, [0], linestyles=line_style4, linewidths=1., colors=line_color4) if area5 is not None: cs5 = m.contour(x, y, area5, [0], linestyles=line_style5, linewidths=1., colors=line_color5) if area6 is not None: cs6 = m.contour(x, y, area6, [0], linestyles=line_style6, linewidths=1., colors=line_color6) if area7 is not None: cs7 = m.contour(x, y, area7, [0], linestyles=line_style7, linewidths=1., colors=line_color7) if area8 is not None: cs8 = m.contour(x, y, area8, [0], linestyles=line_style8, linewidths=1., colors=line_color8) if area9 is not None: cs9 = m.contour(x, y, area9, [0], linestyles=line_style9, linewidths=1., colors=line_color9) if area10 is not None: cs10 = m.contour(x, y, area10, [0], linestyles=line_style10, linewidths=.5, colors=line_color10) if area11 is not None: cs11 = m.contour(x, y, area11, [0], linestyles=line_style11, linewidths=.5, colors=line_color11) if area12 is not None: cs12 = m.contour(x, y, area12, [0], linestyles=line_style12, linewidths=.5, colors=line_color12) if area13 is not None: cs13 = m.contour(x, y, area13, [0], linestyles=line_style13, linewidths=.5, colors=line_color13) if stream is not None: print "be careful ..." lons, stream[0] = m.shiftdata(lon, stream[0], lon_0=origin + shift) lons, stream[1] = m.shiftdata(lon, stream[1], lon_0=origin + shift) lons, stream[2] = m.shiftdata(lon, stream[2], lon_0=origin + shift) xxs, yys = m.makegrid(stream[0].shape[1], stream[0].shape[0], returnxy=True)[2:4] st = m.streamplot(xxs, yys, stream[1], stream[2], color="w", cmap=plt.cm.spectral, arrowsize=.5, density=3, linewidth=.5) FP = FontProperties() FP.set_family('times new roman') FP.set_size('%d' % font_size) if uwinds is not None: lons, uwinds = m.shiftdata(lon, uwinds, lon_0=origin + shift) lons, vwinds = m.shiftdata(lon, vwinds, lon_0=origin + shift) u = uwinds v = vwinds #ugrid,newlons = shiftgrid(180.,u,lon,start=False) #vgrid,newlons = shiftgrid(180.,v,lon,start=False) # transform vectors to projection grid. #uproj,vproj,xx,yy = m.transform_vector(ugrid,vgrid,newlons,lat,31,31,returnxy=True,masked=True) # now plot. # scale = Q = m.quiver(x[::asp, ::asp], y[::asp, ::asp], u[::asp, ::asp], v[::asp, ::asp], pivot='mid', units='width', scale=quiverscale) # make quiver key # qk = plt.quiverkey(Q, 0.85, 0.05, 5, '5 m/s', coordinates = 'figure', labelpos='W', labelcolor = 'black', fontproperties = {'family':'times new roman', 'size':'10', 'style':'normal'}) if gc_lat0 is not None: for i in xrange(gc_lat1.shape[0]): if gc_color is None: gc = m.drawgreatcircle(gc_lon0, gc_lat0, gc_lon1[i], gc_lat1[i], linewidth=gc_lw, color=plt.cm.jet(.0001), alpha=.02) else: gc = m.drawgreatcircle( gc_lon0, gc_lat0, gc_lon1[i], gc_lat1[i], linewidth=gc_lw, color=gc_color(int(5 * gdists[i] / gdists.max()) / 5., alpha=.02 + gdists[i] / gdists.max())) if gc_lat2 is not None: for i in xrange(gc_lat2.shape[0]): gc = m.drawgreatcircle(gc_lon0, gc_lat0, gc_lon2[i], gc_lat2[i], linewidth=gc_lw, color=plt.cm.jet(.9999), alpha=.3) if loc is not None: xloc, yloc = m(loc[0], loc[1]) m.plot(xloc, yloc, marker='D', color='r', markersize=0.5) if ms_lat is not None: m.drawmapscale(lat=ms_lat, lon=ms_lon, lon0=0., lat0=0., length=ms_length, barstyle='fancy') if colorbar is True: ticks_font = matplotlib.font_manager.FontProperties( family='times new roman', style='normal', size=font_size, weight='normal', stretch='normal') if gc_cbar == True: cs_fake = plt.contourf(x, y, np.ones_like(dat) * -1e7, gc_contours, cmap=gc_color, extend='neither') cbar = m.colorbar(cs_fake, extend=extend, orientation='horizontal') else: cbar = m.colorbar(cs, extend=extend) if cbar_title is not None: cbar.ax.set_ylabel(cbar_title, fontsize=font_size, family='times new roman') for label in cbar.ax.get_yticklabels(): label.set_fontproperties(ticks_font) if over is not None: cs.cmap.set_over(over) plt.title('%s' % title, fontsize=font_size) return cs
iagenew2 = ma.masked_where((iagenew > 100000), iagenew) landmask = iagenew > 100000 # Create streamplot: sc1 = mp.scatter(xxnew, yynew, c=iagenew2, edgecolor='None', s=10, vmin=0, vmax=1800, cmap='jet') mp.streamplot(xxnew, yynew, unew2, vnew2, density=3, arrowsize=2, arrowstyle='-|>', color='black') mp.scatter(xxnew[landmask], yynew[landmask], c='white', s=10, edgecolor='None', zorder=2) mp.drawmeridians(np.arange(0, 360, 10), labels=[False, False, False, True], zorder=3) mp.drawparallels(np.arange(-90, 90, 10), labels=[False, True, False, False], zorder=3)
import matplotlib.pyplot as plt from osgeo import gdal import numpy map = Basemap( llcrnrlon=-93.7, llcrnrlat=28.0, urcrnrlon=-66.1, urcrnrlat=39.5, projection="lcc", lat_1=30.0, lat_2=60.0, lat_0=34.83158, lon_0=-98.0, ) ds = gdal.Open("../sample_files/wrf.tiff") lons = ds.GetRasterBand(4).ReadAsArray() lats = ds.GetRasterBand(5).ReadAsArray() u10 = ds.GetRasterBand(1).ReadAsArray() v10 = ds.GetRasterBand(2).ReadAsArray() speed = numpy.sqrt(u10 * u10 + v10 * v10) xx, yy = map.makegrid(v10.shape[1], v10.shape[0], returnxy=True)[2:4] map.streamplot(xx, yy, u10, v10, color=speed, cmap=plt.cm.autumn, linewidth=0.5 * speed) map.drawcoastlines(color="0.15") plt.show()
from mpl_toolkits.basemap import Basemap import numpy as np import matplotlib.pyplot as plt m = Basemap(projection='cyl',resolution='i', llcrnrlat=44.30,urcrnrlat=60.5,\ llcrnrlon=4.750,urcrnrlon=18.00) m.drawcoastlines() #m.fillcontinents(color='coral',lake_color='aqua') # draw parallels and meridians. m.drawparallels(np.arange(-90.,91.,5), labels=[True, True, True, False]) m.drawmeridians(np.arange(-180.,181.,5), labels=[True, False, True, True]) #m.drawmapboundary(fill_color='aqua') x = np.linspace(5, 18, 10) y=np.linspace(45, 60, 10) X,Y = np.meshgrid(x, y) U, V = 12*(X-11), 12*(Y-52) #Default parameters, uniform grid m.streamplot(X, Y, U, V) #plt.show() plt.savefig('/home/s.von.hall/seminar/bspstream.png')
def plot_flow_vectors_basemap(lons, lats, uu, vv, flow_speed, subregion: list = None, grid_shape=None, ax: Axes = None, streamplot=False, draw_colorbar=True): from mpl_toolkits.basemap import Basemap if grid_shape is None: grid_shape = (300, 300) if subregion is None: subregion = [0, 1, 0, 1] if ax is None: fig = plt.figure() nx, ny = lons.shape b = Basemap(lon_0=180, llcrnrlon=lons[35, 35], llcrnrlat=lats[35, 35], urcrnrlon=lons[nx // 2, ny // 2], urcrnrlat=lats[nx // 2, ny // 2], resolution="i", area_thresh=2000) # im = b.pcolormesh(xx, yy, flow_speed) # b.colorbar(im) stride = 6 uu1, vv1 = b.rotate_vector(uu, vv, lons, lats) lons_g, lats_g, xx_g, yy_g = b.makegrid(*grid_shape, returnxy=True) nx, ny = lons_g.shape i_start, i_end = int(nx * subregion[0]), int(nx * subregion[1]) j_start, j_end = int(ny * subregion[2]), int(ny * subregion[3]) xt, yt, zt = lat_lon.lon_lat_to_cartesian(lons_g.flatten(), lats_g.flatten()) xs, ys, zs = lat_lon.lon_lat_to_cartesian(lons.flatten(), lats.flatten()) ktree = KDTree(data=list(zip(xs, ys, zs))) dists, inds = ktree.query(list(zip(xt, yt, zt))) uu_to_plot = uu1.flatten()[inds].reshape(lons_g.shape) vv_to_plot = vv1.flatten()[inds].reshape(lons_g.shape) flow_speed_to_plot = flow_speed.flatten()[inds].reshape(lons_g.shape) clevs = [0, 0.01, 0.02, 0.04, 0.06, 0.08, 0.12, 0.16] ncolors = len(clevs) - 1 norm = BoundaryNorm(clevs, ncolors) cmap = cm.get_cmap("gist_ncar_r", ncolors) im = b.pcolormesh(xx_g, yy_g, flow_speed_to_plot, alpha=0.5, cmap=cmap, norm=norm) if not streamplot: b.quiver(xx_g[i_start:i_end:stride, j_start:j_end:stride], yy_g[i_start:i_end:stride, j_start:j_end:stride], uu_to_plot[i_start:i_end:stride, j_start:j_end:stride], vv_to_plot[i_start:i_end:stride, j_start:j_end:stride], headlength=2, headaxislength=2, headwidth=4, units="inches", color="k") else: b.streamplot(xx_g, yy_g, uu_to_plot, vv_to_plot, linewidth=0.4, density=3, arrowstyle="fancy", arrowsize=0.4, ax=ax, color="k") # im = b.contourf(xx_g, yy_g, flow_speed_to_plot, levels=clevs, alpha=0.5, cmap=cmap, norm=norm) cb = b.colorbar(im, location="bottom") cb.ax.set_visible(draw_colorbar) b.drawcoastlines(linewidth=0.3, ax=ax) if ax is None: fig.savefig("nemo/circ_annual_mean_basemap.png", bbox_inches="tight", dpi=300) plt.close(fig) return im