def make_straits_map(): """ Makes a map of the Straits. """ map = Basemap(resolution='i', projection='tmerc', lat_0 = 51.1515367, lon_0 = -0.8575194,llcrnrlon=-0.871, llcrnrlat=51.148, urcrnrlon=-0.846, urcrnrlat=51.159)#, epsg=4326) folder_list = ['su73ne.shp', 'su74se.shp', 'su83nw.shp', 'su84sw.shp'] subfolder_list = ['Area', 'Line', 'RoadCLine', 'Text', 'VectorMapPoint'] for x in folder_list: for t in subfolder_list: if t=='Line': map.readshapefile(x+'/'+t, 'out', color='b', linewidth=0.3) else: map.readshapefile(x+'/'+t, 'out', linewidth=0.7) map.drawmapscale(-0.8690655121821721, 51.149290623473476, 0, 0, 100, units='m') return map
def plotBase(fig, dt=None): m = Basemap(projection='merc', lon_0=0,lat_0=0,lat_ts=0, llcrnrlat=0,urcrnrlat=50, llcrnrlon=-100,urcrnrlon=-50, resolution='l') m.drawcountries(linewidth=1, color='k') m.drawmapscale(-90, 5, -90, 5, 1000, barstyle='fancy') m.bluemarble(scale=1) # Get Position of NYC, longitude -74.0064, latitude 40.7142 x,y = m(-74.0064, 40.7142) # Plot NYC m.scatter(x, y, s=100, marker='*', color='0.5', alpha=1) plt.text(x,y,'NYC', fontsize='15') if dt is not None: m.nightshade(dt, alpha = 0.3) return m
def draw_map(lon_column, lat_column, subplot=1, cmap='Blues'): plt.subplot(2, 1, subplot) m = Basemap(projection='merc', resolution = 'h', urcrnrlon=-8.5363740000000004, urcrnrlat=41.237622000000002, llcrnrlon=-8.6920289999999998, llcrnrlat=41.112071999999998) m.readshapefile('./data/roads', 'landmarks') m.drawcoastlines() m.drawrivers() m.drawcountries() m.drawmapboundary() lon_bins = np.linspace(lon_column.min() - 1, lon_column.max() + 1, 500) lat_bins = np.linspace(lat_column.min() - 1, lat_column.max() + 1, 500) density, _, _ = np.histogram2d(lat_column, lon_column, [lat_bins, lon_bins]) lon_bins_2d, lat_bins_2d = np.meshgrid(lon_bins, lat_bins) xs, ys = m(lon_bins_2d, lat_bins_2d) plt.pcolormesh(xs, ys, density, cmap=plt.get_cmap(cmap)) plt.colorbar(orientation='horizontal') m.scatter(lon_column.tolist(), lat_column.tolist(), alpha=0.00125, latlon=True, c='green') m.drawmapscale(-8.685, 41.14, -8.685, 41.14, 1)
circ3 = Line2D([0], [0], linestyle="none", marker="s", markersize=10, markerfacecolor=colors[1],alpha=a_val) circ4 = Line2D([0], [0], linestyle="none", marker="s", markersize=10, markerfacecolor=colors[2],alpha=a_val) fig,(ax,ax1,ax2)= plt.subplots(ncols=3) m = Basemap(projection='merc', epsg=cs2cs_args.split(':')[1], llcrnrlon=np.min(glon-0.0004), llcrnrlat=np.min(glat-0.0004), urcrnrlon=np.max(glon+0.0008), urcrnrlat=np.max(glat+0.0004),ax=ax) m.wmsimage(server='http://grandcanyon.usgs.gov/arcgis/services/Imagery/ColoradoRiverImageryExplorer/MapServer/WmsServer?', layers=['3'], xpixels=1000) x,y = m.projtran(glon, glat) m.contourf(x,y,lsq_data.T, cmap='RdYlGn',levels=[0,1,2,3]) m.drawmapscale(np.min(glon)+0.001, np.min(glat)+0.0030, np.min(glon), np.min(glat), 200., units='m', barstyle='fancy', labelstyle='simple', fontcolor='black') ax.legend((circ1, circ3,circ4), ("1 = sand", "2 = gravel","3 = boulders"), numpoints=1, loc=1, borderaxespad=0., fontsize=8) m = Basemap(projection='merc', epsg=cs2cs_args.split(':')[1], llcrnrlon=np.min(glon-0.0004), llcrnrlat=np.min(glat-0.0004), urcrnrlon=np.max(glon+0.0008), urcrnrlat=np.max(glat+0.0004),ax=ax1) m.wmsimage(server='http://grandcanyon.usgs.gov/arcgis/services/Imagery/ColoradoRiverImageryExplorer/MapServer/WmsServer?', layers=['3'], xpixels=1000) x,y = m.projtran(glon, glat) m.contourf(x,y,gmm2_data.T, cmap='RdYlGn',levels=[0,1,2,3]) m.drawmapscale(np.min(glon)+0.001, np.min(glat)+0.0030, np.min(glon), np.min(glat), 200., units='m', barstyle='fancy', labelstyle='simple', fontcolor='black') ax1.legend((circ1, circ4), ("1 = sand", "3 = boulders"), numpoints=1, loc=1, borderaxespad=0., fontsize=8) m = Basemap(projection='merc',
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
(1.0, 0.9, 1.0) ), 'green':( (0.0, 1.0, 1.0), (1.0, 0.03, 0.0) ), 'blue': ( (0.0, 1.0, 1.0), (1.0, 0.16, 0.0) ) } custom_map = LinearSegmentedColormap('custom_map', cdict) plt.register_cmap(cmap=custom_map) # add histogram squares and a corresponding colorbar to the map: plt.pcolormesh(xs, ys, density, cmap="custom_map") cbar = plt.colorbar(orientation='horizontal', shrink=0.625, aspect=20, fraction=0.2,pad=0.02) cbar.set_label('Number of earthquakes',size=18) #plt.clim([0,100]) # translucent blue scatter plot of epicenters above histogram: x,y = m(lons, lats) m.plot(x, y, 'o', markersize=5,zorder=6, markerfacecolor='#424FA4',markeredgecolor="none", alpha=0.33) # http://matplotlib.org/basemap/api/basemap_api.html#mpl_toolkits.basemap.Basemap.drawmapscale m.drawmapscale(-119-6, 37-7.2, -119-6, 37-7.2, 500, barstyle='fancy', yoffset=20000) # make image bigger: plt.gcf().set_size_inches(15,15) plt.show()
def plot_old(self,**kargs): import pylab as pl bathy = kargs.get('bathy','contourf') hvals = kargs.get('hvals','auto') resolution = kargs.get('res','i') rivers = kargs.get('rivers',False) parallels = kargs.get('parallels','auto') meridians = kargs.get('meridians','auto') scale = kargs.get('scale',False) states = kargs.get('states',False) xlim = kargs.get('xlim',False) ylim = kargs.get('ylim',False) title = kargs.get('title','auto') cmap = kargs.get('cmap',pl.cm.gist_earth_r) proj = kargs.get('proj','merc') ax = kargs.get('ax',False) if not ax: fig=pl.figure() ax=pl.axes() else: fig=ax.figure h=np.ma.masked_where(self.mask==0,self.h) xb,yb=self.border() xt=ticks.loose_label(self.lon.min(),self.lon.max()) yt=ticks.loose_label(self.lat.min(),self.lat.max()) ht=ticks.loose_label_n(self.h.min(),self.h.max(),7) if xlim: Lonlims=xlim else: Lonlims=xt[0],xt[-1] if ylim: Latlims=ylim else: Latlims=yt[0],yt[-1] if hvals=='auto': hvals=ht if parallels=='auto': parallels=yt if meridians=='auto': meridians=xt if Basemap and proj: key=Lonlims,Latlims,proj,resolution if not hasattr(self,'_proj'): self._proj={} if self._proj.has_key(key): m=self._proj[key] else: m = Basemap(projection=proj,lat_ts=0.0, #lon_0=self.lon[0].mean(), resolution=resolution, urcrnrlon=Lonlims[1], urcrnrlat=Latlims[1], llcrnrlon=Lonlims[0], llcrnrlat=Latlims[0]) self._proj[key]=m m.drawcoastlines(ax=ax) m.fillcontinents(ax=ax,color=(0.7604, 1.0000, 0.7459)) if rivers: m.drawrivers(color='b') m.drawcountries(ax=ax) # m.drawlsmask() # m.drawmapboundary() if scale: dx=Lonlims[1]-Lonlims[0] dy=Latlims[1]-Latlims[0] lon=Lonlims[1]-dx/10 lat=Latlims[0]+dy/10 lon0=lon lat0=lat length=100 m.drawmapscale(lon,lat,lon0,lat0,length,ax=ax) if states: m.drawstates(ax=ax) m.drawparallels(parallels, labels=[1,0,0,0],ax=ax) m.drawmeridians(meridians, labels=[0,0,0,1],ax=ax) x, y = m(self.lon, self.lat) pch=False if bathy in ['pcolor','pcolormesh']: pch = ax.pcolormesh(x,y,h,cmap=cmap) elif bathy=='contour': pch = ax.contour(x,y,h,hvals,cmap=cmap) elif bathy=='contourf': pch = ax.contourf(x,y,h,hvals,cmap=cmap) if pch: if m.xmax-m.xmin>m.ymax-m.ymin: orientation='horizontal' else: orientation='vertical' cbh = pl.colorbar(pch,orientation=orientation,ax=ax) cbh.set_label('Depth',fontsize=10) if title=='auto': title=self.name if len(title)>80: font=8 elif len(title)>60: font=9 else: font=10 ax.set_title(title,fontsize=font) xb, yb = m(xb,yb) ax.plot(xb,yb) ax.axis([m.xmin, m.xmax, m.ymin, m.ymax]) return m else: ax.pcolormesh(self.lon,self.lat,h,cmap=cmap) ax.contour(self.lon,self.lat,self.h,hvals,colors='w') ax.plot(xb,yb)
def plotIce(di, u, name, direc, coords = None, cells = None, u2 = None, u2_levels = None, u2_color = 'k', u2_linewidth = 1.0, title = '', cmap = 'gist_yarg', scale = 'lin', umin = None, umax = None, numLvls = 12, drawGridLabels = True, levels = None, levels_2 = None, tp = False, tpAlpha = 0.5, contour_type = 'filled', params = None, extend = 'neither', show = True, ext = '.pdf', res = 150, cb = True, cb_format = '%.1e', zoom_box = False, zoom_box_kwargs = None, plot_pts = None, plot_texts = None, plot_continent = False, cont_plot_params = None, drawcoastlines = True, box_params = None): """ Args: :di: DataInput object with desired projection :u: solution to plot; can be either a function on a 2D mesh, or a string key to matrix variable in ``di``.data. :name: title of the plot, latex accepted :direc: directory string location to save image. :cmap: colormap to use - see images directory for sample and name :scale: scale to plot, either 'log', 'lin', or 'bool' :numLvls: number of levels for field values :levels: manual levels, if desired. :tp: boolean determins plotting of triangle overlay :tpAlpha: alpha level of triangles 0.0 (transparent) - 1.0 (opaque) :extends: for the colorbar, extend upper range and may be ["neither", "both", "min", "max"]. default is "neither". for plotting the zoom-box, make ``zoom_box`` = True and supply dict *zoom_box_kwargs* with parameters :zoom: ammount to zoom :loc: location of box :loc1: loc of first line :loc2: loc of second line :x1: first x-coord :y1: first y-coord :x2: second x-coord :y2: second y-coord :scale_font_color: scale font color :scale_length: scale length in km :scale_loc: 1=top, 2=bottom :plot_grid: plot the triangles :axes_color: color of axes :plot_points: dict of points to plot Returns: A sigle *direc/name.ext* in the source directory. """ #FIXME: re-factor this method to take generic kwargs for each method called, # and generally improve readability. # get the original projection coordinates and data : if isinstance(u, str): s = "::: plotting %s's \"%s\" field data directly :::" % (di.name, u) print_text(s, '242') x, y = np.meshgrid(di.x, di.y) v = di.data[u] # if 'u' is a NumPy array and the cell arrays and coordinates are supplied : elif (type(u) == np.ndarray or type(u) == list or type(u) == tuple) \ and len(coords) == 2: x = coords[0] y = coords[1] v = u if type(cells) == np.ndarray: fi = cells else: fi = [] # if there are multiple components to 'u', it is a vector : if len(np.shape(u)) > len(np.shape(x)): vec = True # used for plotting below vx = u[0] vy = u[1] # compute norm : v = 0 for k in u: v += k**2 v = np.sqrt(v + 1e-16) # if 'u' is a NumPy array and cell/coordinate arrays are not supplied : elif (type(u) == np.ndarray or type(u) == list or type(u) == tuple) \ and coords is None: print_text(">>> numpy arrays require `coords' <<<", 'red', 1) sys.exit(1) elif isinstance(u, Function) \ or isinstance(u, dolfin.functions.function.Function): s = "::: plotting FEniCS Function \"%s\" :::" % name print_text(s, '242') mesh = u.function_space().mesh() coord = mesh.coordinates() fi = mesh.cells() v = u.compute_vertex_values(mesh) x = coord[:,0] y = coord[:,1] # get the projection info : if isinstance(di, dict) and 'pyproj_Proj' in list(di.keys()) \ and 'continent' in list(di.keys()): lon,lat = di['pyproj_Proj'](x, y, inverse=True) cont = di['continent'] elif isinstance(di, DataInput): lon,lat = di.proj(x, y, inverse=True) cont = di.cont else: s = ">>> plotIce REQUIRES A 'DataFactory' DICTIONARY FOR " + \ "PROJECTION STORED AS KEY 'pyproj_Proj' AND THE CONTINENT TYPE " + \ "STORED AS KEY 'continent' <<<" print_text(s, 'red', 1) sys.exit(1) # Antarctica : if params is None: if cont is 'antarctica': w = 5513335.22665 h = 4602848.6605 fig = plt.figure(figsize=(7,5)) ax = fig.add_subplot(111) lon_0 = 0 lat_0 = -90 # new projection : m = Basemap(ax=ax, width=w, height=h, resolution='h', projection='stere', lat_ts=-71, lon_0=lon_0, lat_0=lat_0) offset = 0.015 * (m.ymax - m.ymin) # draw lat/lon grid lines every 5 degrees. # labels = [left,right,top,bottom] if drawGridLabels: mer_lab = [True, False, True, True] par_lab = [True, False, True, True] else: mer_lab = [False, False, False, False] par_lab = [False, False, False, False] m.drawmeridians(np.arange(0, 360, 20.0), color = 'black', linewidth = 0.5, labels = mer_lab, fontsize = 8) m.drawparallels(np.arange(-90, 90, 5.0), color = 'black', linewidth = 0.5, labels = par_lab, fontsize = 8) m.drawmapscale(-130, -68, 0, -90, 1000, yoffset = offset, barstyle = 'fancy') # Greenland : elif cont is 'greenland': w = 1532453.49654 h = 2644074.78236 fig = plt.figure(figsize=(7,10)) ax = fig.add_subplot(111) lon_0 = -41.5 lat_0 = 71 # new projection : m = Basemap(ax=ax, width=w, height=h, resolution='h', projection='stere', lat_ts=71, lon_0=lon_0, lat_0=lat_0) offset = 0.010 * (m.ymax - m.ymin) if drawGridLabels: mer_lab = [False, False, False, True] par_lab = [True, False, True, False] else: mer_lab = [False, False, False, False] par_lab = [False, False, False, False] # draw lat/lon grid lines every 5 degrees. # labels = [left,right,top,bottom] m.drawmeridians(np.arange(0, 360, 5.0), color = 'black', labels = mer_lab, fontsize = 8) m.drawparallels(np.arange(-90, 90, 5.0), color = 'black', labels = par_lab, fontsize = 8) m.drawmapscale(-34, 60.5, -41.5, 71, 400, yoffset = offset, barstyle = 'fancy') elif type(params) is dict: llcrnrlat = params['llcrnrlat'] urcrnrlat = params['urcrnrlat'] llcrnrlon = params['llcrnrlon'] urcrnrlon = params['urcrnrlon'] scale_color = params['scale_color'] scale_length = params['scale_length'] scale_loc = params['scale_loc'] figsize = params['figsize'] lat_interval = params['lat_interval'] lon_interval = params['lon_interval'] plot_grid = params['plot_grid'] plot_scale = params['plot_scale'] axes_color = params['axes_color'] if cont is 'greenland': lon_0 = -41.5 lat_0 = 71 elif cont is 'antarctica': lon_0 = 0 lat_0 = -90 fig = plt.figure(figsize=figsize) ax = fig.add_subplot(111) # new projection : m = Basemap(ax=ax, llcrnrlat=llcrnrlat, urcrnrlat=urcrnrlat, llcrnrlon=llcrnrlon, urcrnrlon=urcrnrlon, resolution='h', projection='stere', lon_0=lon_0, lat_0=lat_0) offset = 0.015 * (m.ymax - m.ymin) # draw lat/lon grid lines every degree. # labels = [left,right,top,bottom] if plot_grid: m.drawmeridians(np.arange(0, 360, lon_interval), color = 'black', labels = [True, False, True, True], linewidth = 0.5, fontsize = 8) m.drawparallels(np.arange(-90, 90, lat_interval), color = 'black', labels = [True, False, True, True], linewidth = 0.5, fontsize = 8) else: ax.set_xticklabels([]) ax.set_yticklabels([]) ax.xaxis.set_ticks_position('none') ax.yaxis.set_ticks_position('none') if scale_loc == 1: y_fact = 1.8 x_fact = 1.0 elif scale_loc == 2: y_fact = 0.2 x_fact = 1.0 elif scale_loc == 3: y_fact = 1.8 x_fact = 0.25 if plot_scale : dx = (m.xmax - m.xmin)/2.0 dy = (m.ymax - m.ymin)/2.0 xmid = m.xmin + x_fact*dx ymid = m.ymin + y_fact*dy slon, slat = m(xmid, ymid, inverse=True) m.drawmapscale(slon, slat, slon, slat, scale_length, barstyle = 'simple', linewidth=1.5, fontcolor=scale_color) for axis in ['top','bottom','left','right']: ax.spines[axis].set_color(axes_color) ax.spines[axis].set_linewidth(1.5) else: s = ">>> plotIce REQUIRES A 'dict' OF SPECIFIC PARAMETERS FOR 'custom' <<<" print_text(s, 'red', 1) sys.exit(1) # convert to new projection coordinates from lon,lat : x, y = m(lon, lat) if drawcoastlines: m.drawcoastlines(linewidth=0.5, color = 'black') #m.shadedrelief() #m.bluemarble() #m.etopo() if plot_continent: if cont is 'greenland': llcrnrlat = 57 urcrnrlat = 80.1 llcrnrlon = -57 urcrnrlon = 15 axcont = inset_locator.inset_axes(ax, **cont_plot_params) axcont.xaxis.set_ticks_position('none') axcont.yaxis.set_ticks_position('none') # continent projection : mc = Basemap(ax=axcont, llcrnrlat=llcrnrlat, urcrnrlat=urcrnrlat, llcrnrlon=llcrnrlon, urcrnrlon=urcrnrlon, resolution='c', projection='stere', lon_0=lon_0, lat_0=lat_0) mc.drawcoastlines(linewidth=0.5, color='black') x_c, y_c = mc(lon, lat) v_cont = v.copy() v_cont[:] = 1.0 axcont.tricontourf(x_c, y_c, fi, v_cont, cmap=pl.get_cmap('Reds')) #============================================================================= # plotting : if umin != None and levels is None: vmin = umin elif levels is not None: vmin = levels.min() else: vmin = np.nanmin(v) if umax != None and levels is None: vmax = umax elif levels is not None: vmax = levels.max() else: vmax = np.nanmax(v) # set the extended colormap : cmap = pl.get_cmap(cmap) #cmap.set_under(under) #cmap.set_over(over) # countour levels : if scale == 'log': if levels is None: levels = np.logspace(np.log10(vmin), np.log10(vmax), numLvls) v[v < vmin] = vmin + 2e-16 v[v > vmax] = vmax - 2e-16 formatter = LogFormatter(10, labelOnlyBase=False) norm = colors.LogNorm() # countour levels : elif scale == 'sym_log': if levels is None: levels = np.linspace(vmin, vmax, numLvls) v[v < vmin] = vmin + 2e-16 v[v > vmax] = vmax - 2e-16 formatter = LogFormatter(e, labelOnlyBase=False) norm = colors.SymLogNorm(vmin=vmin, vmax=vmax, linscale=0.001, linthresh=0.001) elif scale == 'lin': if levels is None: levels = np.linspace(vmin, vmax, numLvls) norm = colors.BoundaryNorm(levels, cmap.N) elif scale == 'bool': v[v < 0.0] = 0.0 levels = [0, 1, 2] norm = colors.BoundaryNorm(levels, cmap.N) # please do zoom in! if zoom_box: zoom = zoom_box_kwargs['zoom'] loc = zoom_box_kwargs['loc'] loc1 = zoom_box_kwargs['loc1'] loc2 = zoom_box_kwargs['loc2'] llcrnrlat = zoom_box_kwargs['llcrnrlat'] urcrnrlat = zoom_box_kwargs['urcrnrlat'] llcrnrlon = zoom_box_kwargs['llcrnrlon'] urcrnrlon = zoom_box_kwargs['urcrnrlon'] plot_zoom_scale = zoom_box_kwargs['plot_zoom_scale'] scale_font_color = zoom_box_kwargs['scale_font_color'] scale_length = zoom_box_kwargs['scale_length'] scale_loc = zoom_box_kwargs['scale_loc'] plot_grid = zoom_box_kwargs['plot_grid'] axes_color = zoom_box_kwargs['axes_color'] zb_plot_pts = zoom_box_kwargs['plot_points'] x1, y1 = m(llcrnrlon, llcrnrlat) x2, y2 = m(urcrnrlon, urcrnrlat) axins = inset_locator.zoomed_inset_axes(ax, zoom, loc=loc) inset_locator.mark_inset(ax, axins, loc1=loc1, loc2=loc2, fc="none", ec=axes_color) for axis in ['top','bottom','left','right']: axins.spines[axis].set_color(axes_color) #axins.spines[axis].set_linewidth(2) if scale_loc == 1: fact = 1.8 elif scale_loc == 2: fact = 0.2 dx = (x2 - x1)/2.0 dy = (y2 - y1)/2.0 xmid = x1 + dx ymid = y1 + fact*dy slon, slat = m(xmid, ymid, inverse=True) # new projection : mn = Basemap(ax=axins, width=w, height=h, resolution='h', projection='stere', lat_ts=lat_0, lon_0=lon_0, lat_0=lat_0) if plot_zoom_scale: mn.drawmapscale(slon, slat, slon, slat, scale_length, yoffset = 0.025 * 2.0 * dy, barstyle = 'fancy', fontcolor=scale_font_color) if drawcoastlines: mn.drawcoastlines(linewidth=0.5, color = 'black') axins.set_xlim(x1, x2) axins.set_ylim(y1, y2) axins.xaxis.set_ticks_position('none') axins.yaxis.set_ticks_position('none') if isinstance(u, str): #cs = ax.pcolor(x, y, v, cmap=get_cmap(cmap), norm=norm) if contour_type == 'filled': if scale != 'log': cs = ax.contourf(x, y, v, levels=levels, vmin=vmin, vmax=vmax, cmap=cmap, norm=norm, extend=extend) else: cs = ax.contourf(x, y, v, levels=levels, vmin=vmin, vmax=vmax, cmap=cmap, norm=norm) if zoom_box: if scale != 'log': axins.contourf(x, y, v, levels=levels, vmin=vmin, vmax=vmax, cmap=cmap, norm=norm, extend=extend) else: axins.contourf(x, y, v, levels=levels, vmin=vmin, vmax=vmax, cmap=cmap, norm=norm) if contour_type == 'lines': cs = ax.contour(x, y, v, levels=levels, colors='k', vmin=vmin, vmax=vmax,) for line in cs.collections: if line.get_linestyle() != [(None, None)]: line.set_linestyle([(None, None)]) line.set_color('red') line.set_linewidth(1.5) if levels_2 is not None: cs2 = ax.contour(x, y, v, levels=levels_2, colors='k') for line in cs2.collections: if line.get_linestyle() != [(None, None)]: line.set_linestyle([(None, None)]) line.set_color('#c1000e') line.set_linewidth(0.5) ax.clabel(cs, inline=1, colors='k', fmt='%i') if zoom_box: axins.contour(x, y, v, levels=levels, colors='k', vmin=vmin, vmax=vmax) elif isinstance(u, Function) \ or isinstance(u, dolfin.functions.function.Function) \ or (type(u) == np.ndarray or type(u) == list or type(u) == tuple): #cs = ax.tripcolor(x, y, fi, v, shading='gouraud', # cmap=get_cmap(cmap), norm=norm) if contour_type == 'filled': if scale != 'log': cs = ax.tricontourf(x, y, fi, v, levels=levels, vmin=vmin, vmax=vmax, cmap=cmap, norm=norm, extend=extend) else: cs = ax.tricontourf(x, y, fi, v, levels=levels, vmin=vmin, vmax=vmax, cmap=cmap, norm=norm) if zoom_box: if scale != 'log': axins.tricontourf(x, y, fi, v, levels=levels, vmin=vmin, vmax=vmax, cmap=cmap, norm=norm, extend=extend) else: axins.tricontourf(x, y, fi, v, levels=levels, vmin=vmin, vmax=vmax, cmap=cmap, norm=norm) elif contour_type == 'lines': cs = ax.tricontour(x, y, fi, v, linewidths=2.0, vmin=vmin, vmax=vmax, levels=levels, colors='k') for line in cs.collections: if line.get_linestyle() != [(None, None)]: line.set_linestyle([(None, None)]) line.set_color('red') line.set_linewidth(1.5) if levels_2 is not None: cs2 = ax.tricontour(x, y, fi, v, levels=levels_2, vmin=vmin, vmax=vmax, colors='0.30') for line in cs2.collections: if line.get_linestyle() != [(None, None)]: line.set_linestyle([(None, None)]) line.set_color('#c1000e') line.set_linewidth(0.5) ax.clabel(cs, inline=1, colors='k', fmt='%i') if zoom_box: axins.tricontour(x, y, fi, v, levels=levels, vmin=vmin, vmax=vmax, colors='k') axins.clabel(cs, inline=1, colors='k', fmt='%1.2f') if u2 is not None: if isinstance(u2, str): v2 = di.data[u2] csu2 = ax.contour(x, y, v2, levels=u2_levels, linewidths=u2_linewidth, colors=u2_color) elif isinstance(u2, Function) \ or isinstance(u2, dolfin.functions.function.Function): v2 = u2.compute_vertex_values(mesh) csu2 = ax.tricontour(x, y, fi, v2, linewidths=u2_linewidth, levels=u2_levels, colors=u2_color) #for line in csu2.collections: # if line.get_linestyle() != [(None, None)]: # line.set_linestyle([(None, None)]) if plot_pts is not None: lat_a = plot_pts['lat'] lon_a = plot_pts['lon'] sty_a = plot_pts['style'] clr_a = plot_pts['color'] for lat_i, lon_i, sty_i, clr_i in zip(lat_a, lon_a, sty_a, clr_a): x_i, y_i = m(lon_i, lat_i) ax.plot(x_i, y_i, color=clr_i, marker=sty_i) if plot_texts is not None: lat_a = plot_texts['lat'] lon_a = plot_texts['lon'] txt_a = plot_texts['text'] clr_a = plot_texts['color'] for lat_i, lon_i, txt_i, clr_i in zip(lat_a, lon_a, txt_a, clr_a): x_i, y_i = m(lon_i, lat_i) ax.text(x_i, y_i, txt_i, color=clr_i) if box_params is not None: x1,y1 = m(box_params['llcrnrlon'], box_params['llcrnrlat']) x2,y2 = m(box_params['urcrnrlon'], box_params['urcrnrlat']) box_x_s = [x1,x2,x2,x1,x1] box_y_s = [y1,y1,y2,y2,y1] ax.plot(box_x_s, box_y_s, '-', lw=1.0, color=box_params['color']) if zoom_box: if zb_plot_pts is not None: lat_a = zb_plot_pts['lat'] lon_a = zb_plot_pts['lon'] sty_a = zb_plot_pts['style'] clr_a = zb_plot_pts['color'] for lat_i, lon_i, sty_i, clr_i in zip(lat_a, lon_a, sty_a, clr_a): x_i, y_i = m(lon_i, lat_i) axins.plot(x_i, y_i, color=clr_i, marker=sty_i) # plot triangles : if tp == True: tp = ax.triplot(x, y, fi, 'k-', lw=0.2, alpha=tpAlpha) if zoom_box and plot_grid: tpaxins = axins.triplot(x, y, fi, 'k-', lw=0.2, alpha=tpAlpha) # include colorbar : if cb and scale != 'bool': divider = make_axes_locatable(ax)#plt.gca()) cax = divider.append_axes("right", "5%", pad="3%") cbar = fig.colorbar(cs, cax=cax, #format=formatter, ticks=levels, format=cb_format) #cbar = plt.colorbar(cs, cax=cax, format=formatter, # ticks=np.around(levels,decimals=1)) # title : tit = plt.title(title) #tit.set_fontsize(40) plt.tight_layout(rect=[.03,.03,0.97,0.97]) d = os.path.dirname(direc) if not os.path.exists(d): os.makedirs(d) plt.savefig(direc + name + ext, res=res) if show: plt.show() plt.close(fig) return m
# add whatever text you would like to appear 'This is a U.S. map showing ' + var_2_analyze + ' per state.', # set the horizontal/vertical alignment ha='right', va='bottom', # set the size and the color size=10, color='#555555', transform=ax.transAxes) # Draw a map scale m.drawmapscale( #set the coordinates where the scale should appear coords[0] + 0.08, coords[1] + 0.215, coords[0], coords[1], # what is the max value of the scale (here it's set to 25 for 25 miles) 25., barstyle='fancy', labelstyle='simple', fillcolor1='w', fillcolor2='#555555', fontcolor='#555555', zorder=5, # what units would you like to use. Defaults to km units='mi') # set the layout to maximally fit the bounding area plt.tight_layout() # define the size of the figure fig.set_size_inches(20,24) # save the figure. Increase the dpi to increase the quality of the output .png. For example, dpi=1000 is super high quality plt.savefig('US_' + var_2_analyze + '.png', dpi=100, alpha=True)
class NorthPacific_map(object): def __init__(self, data, lat, lon, clevs, view_scale=None, unit=None, cmap=None): from mpl_toolkits.basemap import Basemap, cm view_scale = view_scale if view_scale is not None else 0.5 unit = unit if unit is not None else 'no unit' gray1 = 'grey' gray2 = 'lightgrey' gray3 = 'lightgrey' self.figure = M.figure_axis_xy(10, 6) self.subplot = plt.subplots_adjust(left=0.05, right=0.95, top=0.95, bottom=0) self.map= Basemap(width=13000000,height=8000000, resolution='c',projection='aeqd',\ lat_1=0,lat_2=60,lon_0=180,lat_0=30 ) self.map.fillcontinents(color=gray1, lake_color=gray1) self.map.drawcoastlines(color=gray2) self.map.drawmeridians(np.arange(0, 360, 10), labels=[0, 0, 0, 1], fontsize=12, color=gray3) self.map.drawparallels(np.arange(-90, 90, 15), labels=[1, 0, 0, 0], fontsize=12, color=gray3) # make up some data on a regular lat/lon grid.\ print(lon.shape, lat.shape) if lon.ndim == 2: lon_X = lon lat_X = lat else: lon_X, lat_X = np.meshgrid(lon, lat) print(lon_X.shape, lat_X.shape) x, y = self.map(lon_X, lat_X) self.x = x self.y = y self.data = data self.clevs = clevs #cmap1 = plt.cm.gist_earth(np.linspace(0,1,clevs.size)) #cmap2= LinearSegmentedColormap.from_list("my_colormap", ((0, 1, 0), (1, 0, 0),(1, 1, 1)), N=clevs.size, gamma=1.0) cmap = cmap if cmap is not None else plt.cm.ocean_r self.cs = self.map.contourf(x, y, data, clevs, cmap=cmap) #plt.clabel(self.cs, self.clevs[0:-1:2],inline=1,fontsize=9, fmt='%2.0f', colors='black', rotation=0) # add colorbar. self.cbar = self.map.colorbar(self.cs, location='right', pad="2%") self.cbar.ax.aspect = 100 self.cbar.outline.set_linewidth(0) self.cbar.set_label(unit) self.map.drawmapscale(-135, 17, -5, 17, 1000, fontsize=12) def title(self, title_str): plt.title(title_str, loc='center', y=1.02, fontsize=14) #plt.title('Define the title2', loc='left', y=1, fontsize=12) def add_contourlines(self, clevs=None, color='white', zorder=12): clevs = clevs if clevs is not None else self.clevs[4:-1:3] self.cont = self.map.contour(self.x, self.y, self.data, clevs, colors=color, linestyles='-') self.cbar.add_lines(self.cont) def save(self, name=None, path=None, verbose=True): import datetime import os savepath = path if path is not None else os.path.join( os.path.dirname(os.path.realpath('__file__')), 'plot/') if not os.path.exists(savepath): os.makedirs(savepath) name = name if name is not None else datetime.date.today().strftime( "%Y%m%d_%I%M%p") extension = '.png' full_name = (os.path.join(savepath, name)) + extension plt.savefig(full_name, bbox_inches='tight', format='png', dpi=180) if verbose: print('save with: ', name)
map.plot(x, y, "bo", markersize=5, alpha=.5) # For earthquake events occured on week 2 of January 2015 elif deltaDays < -7: map.plot(x, y, "ro", markersize=4, alpha=.5) # For earthquake events occured on week 1 of January 2015 else: map.plot(x, y, "go", markersize=3, alpha=.5) # ---------------------------------------------------------------------------------- # STEP 5: SET UP EXTRAS # ---------------------------------------------------------------------------------- # Add a map scale atLon = 135 # Longitude position for scale atLat = -18 # Latitude position for scale forLength =1000 # length in km map.drawmapscale(atLon, atLat, atLon, atLat, length=forLength) # Add a north arrow atLon = 96 # Longitude position for north arrow atLat = 10 # Latitude position for north arrow forLength = 2 # length in degrees x, y = map(atLon, atLat) x2, y2 = map(atLon, atLat + forLength) plt.arrow(x, y, 0, y2 - y, fc="k", ec="k", head_width=75000, head_length=75000) # head width and length control size of arrow head plt.text(x, y, "N", verticalalignment="top", horizontalalignment="center") # Add a legend yellow = plt.scatter([], [], s=12, c="yellow", edgecolors="none") blue = plt.scatter([], [], s=10, c="blue", edgecolors="none")
def PlotShape(filename, VAR, fig, ax, plot_params): # pass in paraeters w/ the 'plot_params' object vmin = plot_params.vmin vmax = plot_params.vmax cmap = plot_params.cmap cblab = plot_params.cblab extend = plot_params.extend ticks = plot_params.ticks ticklabels = plot_params.ticklabels tickadjust = plot_params.tickadjust title = plot_params.title # static params ---- ++++ CHANGE ME +++++ shp_path = "./gis_data/" shpfile = "EastRiver_Shapefile" ds = Dataset("./sample_wrf_file_CO.nc") # GEOG FILE xlon = ds.variables['XLONG'][0, :, :] xlat = ds.variables['XLAT'][0, :, :] HGT = ds.variables['HGT'][0, :, :] # PLOTTING GOES BELOW HERE #Read file attributes #atts = file.ncattrsmap_proj = ds.getncattr('MAP_PROJ') dx = ds.getncattr('DX') dy = ds.getncattr('DY') truelat1 = ds.getncattr('TRUELAT1') truelat2 = ds.getncattr('TRUELAT2') cen_lat = ds.getncattr('MOAD_CEN_LAT') cen_lon = ds.getncattr('STAND_LON') mx = ds.getncattr('WEST-EAST_GRID_DIMENSION') my = ds.getncattr('SOUTH-NORTH_GRID_DIMENSION') mz = ds.getncattr('BOTTOM-TOP_GRID_DIMENSION') # ------- Calculations needed for map projection -----# lat_ll = xlat[0, 0] lat_ur = xlat[-1, -1] lon_ll = xlon[0, 0] lon_ur = xlon[-1, -1] width_meters = dx * (mx - 1) height_meters = dy * (my - 1) zoom_lat = 1.0 zoom_lon = 1.0 extra_pad = .25 bmap_args = { 'projection': 'lcc', 'lon_0': cen_lon, 'lat_0': cen_lat, 'lat_1': truelat1, 'lat_2': truelat2, 'llcrnrlat': lat_ll + zoom_lat + 3 * extra_pad, 'urcrnrlat': lat_ur - 1.2 * zoom_lat, 'llcrnrlon': lon_ll + (zoom_lon + 3.0 * extra_pad), 'urcrnrlon': lon_ur - 1.5 * zoom_lon, 'resolution': 'h', 'ax': ax } # Create the basemap m = Basemap(**bmap_args) # native coords for the grid --- needed to plot WRF var x, y = m(xlon, xlat) # Add Coastlines, States, and Country Boundaries parallels = np.round(np.arange(np.round(lat_ll), np.round(lat_ur), .20), 2) meridians = np.round(np.arange(np.round(lon_ll), np.round(lon_ur), .20), 2) # ---------- Basemap map functions options --------# #m.drawcoastlines(linewidth=1.5) m.drawparallels(parallels, labels=[1, 0, 0, 1], fontsize=4, linewidth=.6, color="gray") m.drawmeridians(meridians, labels=[1, 0, 0, 1], fontsize=4, linewidth=.6, color="gray") #m.drawstates() #m.drawmapscale(-115.8,43.20,-114.72,43.20, 50, "fancy") # for the full domain m.drawmapscale(-116.25, 42.85, -114.72, 42.85, 200, "fancy") # for the zoom in # -------- COLORBAR TICK LOGIC -------- # explicitly pass in ticklabels if ticks: # do not use vmin vmax colormap = m.pcolor( x, y, VAR, cmap=plt.cm.get_cmap(cmap)) # vmin=vmin, vmax=vmax) if ticklabels: cb = fig.colorbar(colormap, ticks=ticks, ax=ax, fraction=0.027, pad=0.01, extend=extend) cb.ax.get_yaxis().set_ticks([]) for j, lab in enumerate(ticklabels.values()): k = 1.5 + j * tickadjust cb.ax.text(2.5, k, lab, va='center') else: # there are ticks, but no ticklabels cb = fig.colorbar(colormap, ticks=ticks, ax=ax, fraction=0.030, pad=0.01, extend=extend) # format=formatter cb.set_label(cblab, labelpad=-2, fontsize=5) cb.ax.tick_params(labelsize=5) # ticks are not explicitly passed in; use vmin vmax instead else: colormap = m.pcolor(x, y, VAR, cmap=plt.cm.get_cmap(cmap), vmin=vmin, vmax=vmax) cb = fig.colorbar(colormap, ax=ax, fraction=0.064, pad=0.01, extend=extend) # format=formatter cb.set_label(cblab, labelpad=-2, fontsize=8, rotation=90) cb.ax.tick_params(labelsize=5) # Read in the shapefile m.readshapefile(shp_path + shpfile, shpfile) patches = [] for shape in getattr(m, shpfile): patches.append(Polygon(np.array(shape), True)) ax.add_collection( PatchCollection(patches, facecolor=None, edgecolor='k', linewidths=1., alpha=0, zorder=2)) # DRAW TERRAIN CONTOURS contourLines = m.contour(x, y, HGT, [2500., 3000., 3500.], linewidths=.4, colors='black', alpha=0.3) ax.clabel(contourLines, inline=1, fontsize=5, fmt={ 2500.: '2.5km', 3000.: '3km', 3500.0: '3.5km' })
x1 = 0.0005 my_fontsize = 20 fig, axes = plt.subplots(1, 4, figsize=(15.3, 8.27)) m1 = Basemap(projection='lcc', lat_0=lats_d01.mean(), lon_0=lons_d01.mean(), llcrnrlon=(-123), llcrnrlat=(58), urcrnrlon=(-108), urcrnrlat=(62), resolution='f', ax=axes[0]) m1.drawcoastlines(linewidth=0.3) m1.drawcountries() m1.drawmapscale(-121, 58.7, lons_d01.mean(), lats_d01.mean(), 100) m1.drawparallels(np.arange(-50, 70, 5), linewidth=0.5, labels=[True, False, False, False], fontsize=20) m1.drawmeridians(np.arange(-130, -100, 5), linewidth=0.5, labels=[False, False, False, False], fontsize=20) map1 = m1.pcolormesh(lons_d01, lats_d01, avg_daily_obs_d01, latlon=True, cmap=newcmp) axes[0].set_title('G4ICE - 9 km\n', fontsize=30) mstats = 'm = %.4f, s = %.4f' % (np.nanmean(avg_daily_obs_d01),
k, ha='center', va='center', size=6, color='black') if radius < 2: scaleLen = round(radius * 4) / 8 * 1000 else: scaleLen = round(radius / 2) * 1000 # Draw a map scale m.drawmapscale( coords[0] + w * 0.2, coords[1] + h * 0.1, coords[0], coords[1], int(scaleLen), # length in meters barstyle='fancy', labelstyle='simple', units='m', fillcolor1='w', fillcolor2='#555555', fontcolor='#555555', zorder=4) plt.title("Parcels in Oakland with an error") plt.tight_layout() # this will set the image width to 722px at 100dpi fig.set_size_inches(7.22, 5.25) # use for larger size plt.savefig('data/Oakland_temp.png', dpi=300, alpha=True) plt.show()
llcrnrlat=minlatitude,urcrnrlat=maxlatitude,llcrnrlon=minlongitude,\ urcrnrlon=maxlongitude,lat_ts=45) #m.bluemarble() #m.etopo() #m.shadedrelief() m.drawcountries(linewidth=0.5) m.drawcoastlines(linewidth=0.5) m.fillcontinents(color='#cc9955', lake_color='aqua') m.drawmapboundary(fill_color='aqua') #m.drawmapboundary() # draw a line around the map region #below gives grids m.drawparallels(np.arange(-90., 120., 5.), labels=[1, 0, 0, 0]) # draw parallels m.drawmeridians(np.arange(60., 190., 5.), labels=[0, 0, 0, 1]) # draw meridians m.drawmapscale(120, -42.5, 50, 180, 1000, barstyle='fancy') x, y = m(lons, lats) m.plot(x, y, '^', label="station", markersize=5, color='k') plt.title("Plot of station pairs for all UM Gippsland seismometers") lg = plt.legend() lg.get_frame().set_facecolor('grey') plt.show()
def generate_figure(): # set up plot plt.clf() fig = plt.figure(figsize=(8, 8)) ax = fig.add_subplot(111, axisbg='w', frame_on=False) norm = Normalize() lllon = min(longitudeValues) - 1 lllat = min(latitudeValues) - 1 urlon = max(longitudeValues) + 1 urlat = max(latitudeValues) + 1 scale_min = min(magnitudeValues) scale_max = max(magnitudeValues) # Set up Basemap instance m = Basemap( projection = 'merc', llcrnrlon = lllon, llcrnrlat = lllat, urcrnrlon = urlon, urcrnrlat = urlat, resolution='h') # transform lon / lat coordinates to map projection projected_lon, projected_lat = m(*(longitudeValues, latitudeValues)) # grid data numcols, numrows = 1000, 1000 xi = np.linspace(min(projected_lon), max(projected_lon), numcols) yi = np.linspace(min(projected_lat), max(projected_lat), numrows) xi, yi = np.meshgrid(xi, yi) # interpolate x, y, z = projected_lon, projected_lat, magnitudeValues zi = griddata(x, y, z, xi, yi, interp='linear') # draw map details m.drawmapboundary(fill_color = '#3f6077') m.fillcontinents(color='#ffbfa7', lake_color='#7093DB') m.drawcountries( linewidth=.75, linestyle='solid', color='#000073', antialiased=True, ax=ax, zorder=3) m.drawparallels( np.arange(lllat, urlat, 2.), color = 'black', linewidth = 0.5, labels=[True, False, False, False]) m.drawmeridians( np.arange(lllon, urlon, 2.), color = '0.25', linewidth = 0.5, labels=[False, False, False, True]) levels = np.linspace(scale_min,scale_max ,20) # contour plot con = m.contourf(xi, yi, zi, zorder=4, alpha=0.6, cmap='RdPu', levels=levels) # scatter plot m.scatter( projected_lon, projected_lat, color='#000054', edgecolor='#fffddf', alpha=.75, s=100 * norm(magnitudeValues), cmap='RdPu', ax=ax, vmin=zi.min(), vmax=zi.max(), zorder=10) # add colour bar and title # add colour bar, title, and scale cbar = plt.colorbar(con, orientation='vertical', fraction=.057, pad=0.05) cbar.set_label("Richter Scale - Mw") m.drawmapscale( 24., -9., 28., -13, 100, units='km', fontsize=10, yoffset=None, barstyle='fancy', labelstyle='simple', fillcolor1='w', fillcolor2='#000000', fontcolor='#000000', zorder=5) plt.title("Earthquake Contour Map") plt.savefig("contour.png", format="png", dpi=300, transparent=True)
# plot boroughs by adding the PatchCollection to the axes instance ax.add_collection(PatchCollection(df_map['patches'].values, match_original=True)) # copyright and source data info #smallprint = ax.text( # 1.03, 0, # 'Total points: %s\nContains Ordnance Survey data\n$\copyright$ Crown copyright and database right 2013\nPlaque data from http://openplaques.org' % len(ldn_points), # ha='right', va='bottom', # size=4, # color='#555555', # transform=ax.transAxes) # Draw a map scale m.drawmapscale( coords[0] + 0.08, coords[1] + 0.015, coords[0], coords[1], 10., barstyle='fancy', labelstyle='simple', fillcolor1='w', fillcolor2='#555555', fontcolor='#555555', zorder=5) plt.title("Tax Parcels in Oakland") plt.tight_layout() # this will set the image width to 722px at 100dpi fig.set_size_inches(7.22, 5.25) plt.savefig('data/Oakland_temp.png', dpi=300, alpha=True) plt.show() #%% Read shape file, filter, and save a smaller size import fiona baseFile = 'data/Oakland_parcels/parcels'
def main(): #-- directory setup #- current directory current_dir = os.path.dirname(os.path.realpath(__file__)) headDirectory = os.path.join(current_dir,'..','FrontLearning_data') glaciersFolder=os.path.join(headDirectory,'Glaciers') glaciers = ['Helheim','Jakobshavn','Kangerlussuaq','Sverdrup'] h_align = ['left','left','left','left'] v_space = [2e5,-6e4,2e5,-5e4] #-- output projection outputCRS = 4326 #(WGS84) #3413 outProj = Proj(init='epsg:'+str(outputCRS)) #-- initialize figure fig, ax1 = plt.subplots(1,1,figsize=(6,6)) ll = {'lat': [58,82],'lon': [302,20]} cent = {'lat': 72.225676431028518, 'lon': 316.18118891332665} #-- ellipsoid parameters for Basemap transformation a_axis = 6378137.0#-- [m] semimajor axis of the ellipsoid flat = 1.0/298.257223563#-- flattening of the ellipsoid rad_e = a_axis*(1.0 -flat)**(1.0/3.0) m = Basemap(ax=ax1, projection='stere',lon_0=cent['lon'], lat_0=cent['lat'], \ lat_ts=70.0, llcrnrlat=ll['lat'][0], urcrnrlat=ll['lat'][1],\ llcrnrlon=ll['lon'][0], urcrnrlon=ll['lon'][1],\ rsphere=rad_e, resolution='h', area_thresh=10) #-- draw coastlines m.drawcoastlines() #-- set up font properties font = FontProperties() font.set_weight('bold') #-- go through each glacier and list the list of months for g,a,v in zip(glaciers,h_align,v_space): if g == 'Helheim': infile = os.path.join(glaciersFolder,g,'%s Image Data_newCorners.csv'%g) else: infile = os.path.join(glaciersFolder,g,'%s Image Data.csv'%g) #-- get corners c = pd.read_csv(infile) x1,x2,x3,x4 = c['ulX'][0],c['urX'][0],c['lrX'][0],c['llX'][0] y1,y2,y3,y4 = c['ulY'][0],c['urY'][0],c['lrY'][0],c['llY'][0] #-- get input projection inputCRS = c['Projection'][0] inProj = Proj(init='epsg:'+str(inputCRS)) x_mean,y_mean = np.mean([x1,x2,x3,x4]),np.mean([y1,y2,y3,y4]) x,y = transform(inProj,outProj,x_mean,y_mean) x_mean,y_mean = m(x,y) ax1.scatter(x_mean,y_mean,s=200,c='dodgerblue',zorder=10) #-- set up text location if a == 'left': x_str = x_mean + 4e4 else: x_str = x_mean - 4e4 y_str = y_mean - v #-- Add glacier name ax1.text(x_str, y_str, g, fontproperties=font, verticalalignment='bottom',\ horizontalalignment=a,color='indigo', fontsize=15) plt.axis('off') m.drawmapboundary(fill_color='aqua') m.fillcontinents(color='peachpuff',lake_color='aqua') m.drawparallels(range(0, 90, 10),labels=[1,0,0,0]) m.drawmeridians(range(0, 360, 20),labels=[0,0,0,1]) m.drawmapscale(305, 60, cent['lon'], cent['lat'], 400, barstyle='fancy') plt.savefig(os.path.join(headDirectory,'Figure_S1-2_map.pdf'),format='pdf') plt.close(fig)
def plotIce( u, cmap="wiki", overlay=None, overlay2=None, overlay_alpha=0.3, overlay_alpha2=0.8, name="No name provided", units="", mesh_plot=False, meshAlpha=0.5, lines=False, ): """ started as a fairly general tool, but has been degrated into something specific for Isunnguata Sermia. Will require a significant overhaul to make it general. Written by: Evan Cummings modified by JVJ INPUTS : u : FeNICS solution object to plot...must be object of type Function. name : title of the plot, latex accepted units : units for the colorbar, latex approved mesh_plot : boolean determins plotting of mesh overlay meshAlpha : alpha level of mesh 0.0 (transparent) - 1.0 (opaque) OUTPUT : A sigle 250 dpi name.png in the source directory. """ filename = inspect.getframeinfo(inspect.currentframe()).filename home = os.path.dirname(os.path.abspath(filename)) # Mesh data needed for plotting mesh = u.function_space().mesh() # Pull mesh coord = mesh.coordinates() # Gather coordinates vx = coord[:, 0] vy = coord[:, 1] fi = mesh.cells() # These are the sets of vertices forming a triangle # Values corresponding to the dataset being plotted v = u.compute_vertex_values(mesh) # Set plot size: fig = plt.figure(figsize=(13.5, 7), dpi=80) ax = fig.add_axes() width = 236.0 * 250 height = 90.0 * 250 # This is the 'new' way to move x,y mesh points to lon,lat. Based on pyproj, instead of basemap. # It seems to work. p = pyproj.Proj( "+proj=stere +lat_0=90 +lat_ts=71 +lon_0=-46 +k=1 +x_0=0 +y_0=0 +no_defs +a=6378137 +rf=298.257223563 +towgs84=0.000,0.000,0.000 +to_meter=1" ) lon, lat = p(vx, vy, inverse=True) # Given original data and projection, place onto projection here that # 'looks' nice m = Basemap( ax=ax, width=width, height=height, resolution="h", projection="stere", lat_ts=71, lon_0=-49.67, lat_0=67.185 ) x, y = m(lon, lat) # Annotations on plot m.drawmeridians(np.arange(-55, -40, 0.25), color="black", labels=[False, False, False, True]) m.drawparallels(np.arange(66, 68, 0.1), color="black") m.drawmapscale(-49.125, 67.097, -49.65, 67.19, 10, yoffset=0.02 * (m.ymax - m.ymin), barstyle="fancy") m.drawmapboundary(fill_color="white") # This has been a major hassle to generalize, mostly due to the colormaps # requiring certain asymmetry about zero, and my incistence that zero be # sealevel levels = np.arange(-3, 0.5, 0.25) from matplotlib import colors from matplotlib.ticker import ScalarFormatter formatter = ScalarFormatter() if cmap == "mby": cdict = gmtColormap(home + "/plothelp/mby.cpt") color_map = colors.LinearSegmentedColormap("color_map", cdict) elif cmap == "wiki": vmin = -550 # These are the topo extents, scaled to make 0 make sense vmax = 1100 norm = colors.Normalize(vmin=vmin, vmax=vmax) levels = np.arange(vmin, vmax, 50) cdict = gmtColormap(home + "/plothelp/wiki-2.0.cpt") color_map = colors.LinearSegmentedColormap("color_map", cdict) elif cmap == "gist_rainbow": vmin = 12.0 # These are the topo extents, scaled to make 0 make sense vmax = 425.0 norm = colors.Normalize(vmin=vmin, vmax=vmax) levels = np.linspace(vmin, vmax, 256) color_map = cm.gist_rainbow ticks = linspace(vmin, vmax, 10).round() else: cdict == gmtColormap(home + "/plothelp/ETOPO1.cpt") color_map = colors.LinearSegmentedColormap("color_map", cdict) norm = colors.Normalize(vmin=vmin, vmax=vmax) cs = tricontourf(x, y, fi, v, norm=norm, cmap=get_cmap(color_map), levels=levels) if mesh_plot == True: mesh_handle = triplot(x, y, fi, "-", lw=0.2, alpha=meshAlpha) if overlay: mesh = overlay.function_space().mesh() # Pull mesh vo = overlay.compute_vertex_values(mesh) vo[vo > 0.0] = 1.0 norm = colors.Normalize(0.0, 1.0) ol = tricontourf(x, y, fi, vo, levels=[0.75, 1.25], alpha=overlay_alpha, cmap=cm.Purples, norm=norm) if overlay2: mesh = overlay2.function_space().mesh() # Pull mesh vo = overlay2.compute_vertex_values(mesh) ol = tricontour(x, y, fi, vo, levels=[12.0], linewidths=2.0, cmap=cm.gist_gray) if lines: print "Adding the radar lines..." # file = open("plothelp/radar_lines_small.txt") file = open(home + "/plothelp/1993_2011_Radar_LL.txt") lon, lat = [], [] count = 0 for line in file.readlines(): sl = line.split("|") if count % 8 == 0: lon.append(float(sl[0])) lat.append(float(sl[1])) count += 1 x, y = m(lon, lat) m.scatter(x, y, linewidth=0.75, marker=".", s=0.6, color="r") try: cbar = m.colorbar(cs, ticks=ticks, location="right", pad="5%") except NameError: cbar = m.colorbar(cs, format=formatter, location="right", pad="5%") txt = figtext(0.873, 0.77, units) txt.set_fontsize(16.0) tit = title(name) tit.set_fontsize(22.0) ll1 = figtext(0.075, 0.275, "67.1$^{\\circ}$N") ll1 = figtext(0.075, 0.527, "67.2$^{\\circ}$N") direc = "images/" + name + ".png" d = os.path.dirname(direc) if not os.path.exists(d): os.makedirs(d) savefig(direc, dpi=120)
def plot_graph_on_map(config_model, G=None, edge_colors=None, edge_labels=None, figsize=(15, 15), fontsize=9, arrow_style='->', rotate_labels=False, bounds=None, scale_left_distance=0.05, scale_bottom_distance=0.05, ax=None, show_scale=True, map_resolution='i'): from mpl_toolkits.basemap import Basemap import networkx as nx from calliope.lib import nx_pylab if all(['lat' in i or 'lon' in i for i in config_model.metadata.location_coordinates.as_dict_flat().keys()]): coord_system = 'geographic' elif all(['x' in x or 'y' in x for x in config_model.metadata.location_coordinates.as_dict_flat().keys()]): coord_system = 'cartesian' else: raise KeyError('unidentified coordinate system. Expecting data in ' 'the format {lat: N, lon: M} or {x: N, y: M} for user ' 'coordinate values of N, M.') # Set up basemap if not bounds: bounds = config_model.metadata.map_boundary # Create plot if not ax: fig = plt.figure(figsize=figsize) ax = fig.add_subplot(111, facecolor='w', frame_on=False) # Node positions pos = config_model.metadata.location_coordinates if coord_system == 'geographic': bounds_width = bounds.upper_right.lon - bounds.lower_left.lon # lon --> width bounds_height = bounds.upper_right.lat - bounds.lower_left.lat # lat --> height m = Basemap(projection='merc', ellps='WGS84', llcrnrlon=bounds.lower_left.lon, llcrnrlat=bounds.lower_left.lat, urcrnrlon=bounds.upper_right.lon, urcrnrlat=bounds.upper_right.lat, lat_ts=bounds.lower_left.lat + bounds_width / 2, resolution=map_resolution, suppress_ticks=True) m.drawmapboundary(fill_color=None, linewidth=0) m.drawcoastlines(linewidth=0.2, color='#626262') pos = {i: m(pos[i].lon, pos[i].lat) for i in pos} # translate lat, lon to basemap positions # Adding node names just above node points pos_offset = {i: (pos[i][0], pos[i][1] + 20) for i in pos} elif coord_system == 'cartesian': pos = {i: (pos[i].x, pos[i].y) for i in pos} # Adding node names just above node points pos_offset = {i: (pos[i][0], pos[i][1] + 0.2) for i in pos} # m has to be defined as it is returned m = None # Draw the graph if G: # Using nx_pylab to be able to set zorder below the edges nx_pylab.draw_networkx_nodes(G, pos, node_color='#CCCCCC', node_size=300, zorder=0) # Using nx_pylab from lib to get arrow_style option nx_pylab.draw_networkx_edges(G, pos, width=3, edge_color=edge_colors, # This works for edge_use edge_vmin=0.0, edge_vmax=1.0, edge_cmap=plt.get_cmap('seismic'), arrows=True, arrow_style=arrow_style) # bbox = dict(color='white', alpha=0.5, edgecolor=None) labels = nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, rotate=rotate_labels, font_size=fontsize) # Adding node names just above node points nx.draw_networkx_labels(G, pos_offset, font_size=fontsize) # Add a map scale if show_scale and coord_system=='geographic': scale = m.drawmapscale( bounds.lower_left.lon + bounds_width * scale_left_distance, bounds.lower_left.lat + bounds_height * scale_bottom_distance, bounds.lower_left.lon, bounds.lower_left.lat, 100, barstyle='simple', labelstyle='simple', fillcolor1='w', fillcolor2='#555555', fontcolor='#555555', fontsize=fontsize ) return ax, m
# convert the bin mesh to map coordinates: xs, ys = my_map(lon_bins_2d, lat_bins_2d) # will be plotted using pcolormesh # define custom colormap, white -> nicered, #E6072A = RGB(0.9,0.03,0.16) cdict = {'red': ( (0.0, 1.0, 1.0), (1.0, 0.9, 1.0) ), 'green':( (0.0, 1.0, 1.0), (1.0, 0.03, 0.0) ), 'blue': ( (0.0, 1.0, 1.0), (1.0, 0.16, 0.0) ) } custom_map = LinearSegmentedColormap('custom_map', cdict) plt.register_cmap(cmap=custom_map) # add histogram squares and a corresponding colorbar to the map: plt.pcolormesh(xs, ys, density, cmap="custom_map") cbar = plt.colorbar(orientation='horizontal', shrink=0.55, aspect=20, fraction=0.2, pad=0.04) cbar.set_label('Number of Tweets',size=10) # add map scale my_map.drawmapscale(-9,49.75,-9,49.75,300,barstyle='fancy') # inrease size of plot #plt.gcf().set_size_inches(10,10) plt.show()
m.drawcoastlines(linewidth=0.25) if inner_titles: for ax in range(0, nt): t = ppt.add_inner_title(fig.axes[ax], inner_titles[ax], loc=2) t.patch.set_ec("none") if drawmapscale: x_c = m.llcrnrx + np.abs(m.urcrnrx - m.llcrnrx) * 0.15 y_c = m.llcrnry + np.abs(m.urcrnry - m.llcrnry) * 0.075 lon_c, lat_c = m(x_c, y_c, inverse=True) ms_width = np.abs(m.urcrnrx - m.llcrnrx) * 0.2 / 1e3 m.drawmapscale(lon_c, lat_c, lon_0, lat_0, ms_width, units="km", fontsize=plt.rcParams["font.size"], barstyle="fancy") contour_colors = ["white", "black"] if shape_filename: for index, shpfile in enumerate(shape_filename): shpfile = shpfile.split(".shp")[0] m.readshapefile(shpfile, "my_shapefile", linewidth=0.75, color=contour_colors[index]) # m.readshapefile(shape_filename.split('.shp')[0], # 'my_shapefile', linewidth=1.1)
addPGdata(query, 1, (btf(189), btf(215), btf(231)), (btf(189), btf(215), btf(231)), True, huc, 1.5, 10, mapobject=m) query = "SELECT ST_Force_2D(b.geom) AS geom1 FROM baselayer_nhd_waterbody b, nhd_hu8_watersheds w WHERE ST_Intersects(ST_Buffer(ST_Envelope(w.geom), 1), b.geom) AND w.huc_8_num = %s" % (huc) addPGdata(query, 1, (btf(189), btf(215), btf(231)), (btf(189), btf(215), btf(231)), True, huc, 1.5, 10, mapobject=m) # States query = "SELECT geom AS geom1 FROM states_project_area" addPGdata(query, 1, (btf(42), btf(42), btf(42)), (btf(222), btf(222), btf(222)), True, '', 0.5, 5, mapobject=m) # A. varicosa data query = "SELECT a.geom AS geom1 FROM avaricosa.polys a WHERE a.huc_8_num = %s" % (huc) addPGdata(query, 1, 'red', 'red', True, huc, 1, 100, mapobject=m) query = "SELECT a.geom AS geom1 FROM avaricosa.points a WHERE a.huc_8_num = %s" % (huc) addPGdata(query, 1, 'red', 'red', True, huc, 1, 100, mapobject=m) query = "SELECT a.geom AS geom1 FROM avaricosa.lines a WHERE a.huc_8_num = %s" % (huc) addPGdata(query, 1, 'red', 'red', True, huc, 1, 100, mapobject=m) # Add the scalebar m.drawmapscale(llx, lly, llx, lly, 10, barstyle='fancy', fontsize=11, labelstyle='simple', zorder=100) ax2 = plt.subplot2grid((3,3), (2,0)) m1 = Basemap(projection='merc',llcrnrlat=36,urcrnrlat=48,\ llcrnrlon=-84,urcrnrlon=-66,lat_ts=42,resolution='l') m1.drawcoastlines() m1.fillcontinents(color=(btf(222), btf(222), btf(222)),lake_color=(btf(189), btf(215), btf(231))) m1.drawcountries() m1.drawstates() m1.drawmapboundary(fill_color=(btf(189), btf(215), btf(231))) query = "SELECT geom AS geom1 FROM nhd_hu8_watersheds WHERE huc_8_num = %s" % (huc) addPGdata(query, 1, 'red', 'white', False, huc, 1.5, 30, mapobject=m1) #ax2.text(0.5, 0.5, 'locus', va="center", ha="center") #plt.gca().text(0.5, 0.5, 'locus', va="center", ha="center") ax3 = plt.subplot2grid((3,3), (2,1), colspan=2) ax3.set_frame_on(False)
def plot_stamp(inargs, fobj, colors, levels, ax, var): """""" jpl0, jpl1, ipl0, ipl1 = (50 + inargs.zoom_lat1, 357 - 51 + inargs.zoom_lat2, 50 + inargs.zoom_lon1, 357 - 51 + inargs.zoom_lon2) data = fobj.data lats = fobj.lats[jpl0:jpl1, ipl0:ipl1] lons = fobj.lons[jpl0:jpl1, ipl0:ipl1] polelat = fobj.polelat polelon = fobj.polelon lllat = lats[0, 0] lllon = lons[0, 0] urlat = lats[-1, -1] urlon = lons[-1, -1] Basemap_kwargs = { \ "projection": "lcc", # the projection "lcc" lets the domain appear as rectangular on the 2D plot "lon_0": polelon, "lat_0": 90. + polelat, "llcrnrlat": lllat, "urcrnrlat": urlat, "llcrnrlon": lllon, "urcrnrlon": urlon, "resolution": 'h', "area_thresh": 10000., } m = Basemap(**Basemap_kwargs) x, y = m(lons, lats) if var == 'PREC_ACCUM': cfplot = m.contourf(x, y, data[jpl0:jpl1, ipl0:ipl1], levels=levels, colors=colors, ax=ax) else: cm_prism = plt.cm.prism cm_prism.set_under(color='white') cfplot = m.imshow(data[jpl0:jpl1, ipl0:ipl1], cmap=cm_prism, origin='lower', vmin=1) m.drawcoastlines() # linewidth=0.1, antialiased=0) m.drawcountries(linewidth=0.1, antialiased=0) if inargs.ind_scale: m.drawmapscale(inargs.ind_scale_pos[0], inargs.ind_scale_pos[1], inargs.ind_scale_pos[0], inargs.ind_scale_pos[1], inargs.ind_scale_len, barstyle='fancy', fontsize=7) if inargs.ind_box: jpl0_box, jpl1_box, ipl0_box, ipl1_box = (50 + inargs.ind_box_lat1, 357 - 51 + inargs.ind_box_lat2, 50 + inargs.ind_box_lon1, 357 - 51 + inargs.ind_box_lon2) lon_bl = fobj.lons[jpl0_box, ipl0_box] lon_br = fobj.lons[jpl0_box, ipl1_box] lon_tl = fobj.lons[jpl1_box, ipl0_box] lon_tr = fobj.lons[jpl1_box, ipl1_box] lat_bl = fobj.lats[jpl0_box, ipl0_box] lat_br = fobj.lats[jpl0_box, ipl1_box] lat_tl = fobj.lats[jpl1_box, ipl0_box] lat_tr = fobj.lats[jpl1_box, ipl1_box] m.plot((lon_bl, lon_br), (lat_bl, lat_br), latlon=True, color='k') m.plot((lon_br, lon_tr), (lat_br, lat_tr), latlon=True, color='k') m.plot((lon_tr, lon_tl), (lat_tr, lat_tl), latlon=True, color='k') m.plot((lon_tl, lon_bl), (lat_tl, lat_bl), latlon=True, color='k') return cfplot
neighborhoods = NeighborhoodLabels() for (k, v) in neighborhoods.items() : pos = m(v[1], v[0]) if window_polygon.contains(Point(pos)) is True : ax.text(pos[0], pos[1], k, ha='center', va='center', size=6, color='black') if radius < 2 : scaleLen = round(radius*4)/8*1000 else : scaleLen = round(radius/2)*1000 # Draw a map scale m.drawmapscale( coords[0] + w * 0.2, coords[1] + h * 0.1, coords[0], coords[1], int(scaleLen), # length in meters barstyle='fancy', labelstyle='simple', units = 'm', fillcolor1='w', fillcolor2='#555555', fontcolor='#555555', zorder=4) plt.title("Parcels in Oakland with an error") plt.tight_layout() # this will set the image width to 722px at 100dpi fig.set_size_inches(7.22, 5.25) # use for larger size plt.savefig('data/Oakland_temp.png', dpi=300, alpha=True) plt.show()
hx = m.hexbin(x, y, C=None, gridsize=(numhexbins, int(numhexbins * h / w)), bins='log', mincnt=1, edgecolor='none', alpha=1., cmap=plt.get_cmap('Blues')) #drawing a scale m.drawmapscale(coords[0] + 0.1, coords[1] + 0.015, coords[0], coords[1], 10, units='km', barstyle='fancy', labelstyle='simple', fontcolor='#555555', zorder=5) fig.suptitle("My location density in Copenhagen", fontdict={ 'size': 24, 'fontweight': 'bold' }, y=0.92) ax.set_title( "Using location data collected from my Android phone via Google Takeout", fontsize=14, y=0.98)
ax = fig.add_subplot(111, axisbg='w', frame_on=False) cmap = plt.get_cmap('Blues') # draw neighborhoods with grey outlines df_map['patches'] = df_map['poly'].map(lambda x: PolygonPatch(x, ec='#111111', lw=.8, alpha=1., zorder=4)) pc = PatchCollection(df_map['patches'], match_original=True) # apply our custom color values onto the patch collection cmap_list = [cmap(val) for val in (df_map.jenks_bins.values - df_map.jenks_bins.values.min())/( df_map.jenks_bins.values.max()-float(df_map.jenks_bins.values.min()))] pc.set_facecolor(cmap_list) ax.add_collection(pc) #Draw a map scale m.drawmapscale(coords[0] + 0.08, coords[1] + -0.01, coords[0], coords[1], 10., fontsize=16, barstyle='fancy', labelstyle='simple', fillcolor1='w', fillcolor2='#555555', fontcolor='#555555', zorder=5, ax=ax,) # ncolors+1 because we're using a "zero-th" color cbar = custom_colorbar(cmap, ncolors=len(jenks_labels)+1, labels=jenks_labels, shrink=0.5) cbar.ax.tick_params(labelsize=16) fig.suptitle(" Time Spent in Seattle Neighborhoods", fontdict={'size':24, 'fontweight':'bold'}, y=0.92) ax.set_title(" Using location data collected from my Android phone via Google Takeout", fontsize=14, y=0.98) ax.text(1.35, 0.04, "Collected from 2012-2014 on Android 4.2-4.4\nGeographic data provided by data.seattle.gov", ha='right', color='#555555', style='italic', transform=ax.transAxes) ax.text(1.35, 0.01, "BeneathData.com", color='#555555', fontsize=16, ha='right', transform=ax.transAxes) plt.savefig('chloropleth.png', dpi=300, frameon=False, transparent=False, bbox_inches='tight', pad_inches=0.5) # <headingcell level=2>
llcrnrlat=minlatitude,urcrnrlat=maxlatitude,llcrnrlon=minlongitude,\ urcrnrlon=maxlongitude,lat_ts=45) #m.bluemarble() #m.etopo() #m.shadedrelief() m.drawcountries(linewidth=0.5) m.drawcoastlines(linewidth=0.5) m.fillcontinents(color='#cc9955',lake_color='aqua') m.drawmapboundary(fill_color='aqua') #m.drawmapboundary() # draw a line around the map region #below gives grids m.drawparallels(np.arange(-90.,120.,5.),labels=[1,0,0,0]) # draw parallels m.drawmeridians(np.arange(60.,190.,5.),labels=[0,0,0,1]) # draw meridians m.drawmapscale(120, -42.5, 50, 180, 1000, barstyle='fancy') x, y = m(lons, lats) m.plot(x, y, '^', label ="station", markersize = 5, color = 'k') plt.title("Plot of station pairs for all UM Gippsland seismometers") lg = plt.legend() lg.get_frame().set_facecolor('grey') plt.show()
#Adicione a linha de costa. m.drawcoastlines(linewidth=1) # Adicione os continentes. m.fillcontinents(color='#000000') # Adicione os paralelos e meridianos . m.drawparallels(np.arange(-90.,120.,10.), linewidth=0.1, dashes = [1,5], color='black', labels=[1,0,0,1],labelstyle="+/-") m.drawmeridians(np.arange(-180.,180.,10.), linewidth=0.1,dashes = [1,5], color='black', labels=[1,0,0,1],labelstyle="+/-") # Adicione países m.drawcountries(color = '#ffffff') # Adicione uma escala ao mapa. m.drawmapscale(-25,-50,lon.min(),lat.max(),1500, barstyle='fancy', units='km', labelstyle='simple',fillcolor1='w'); # Defina para plotar uma variável. kw = dict(levels=range(-5,5,1),cmap=cm.balance,latlon=True) lon,lat = np.meshgrid(lat, lat) Cf = m.contourf(lon,lat,stab,**kw); cbar = plt.colorbar(Cf); cbar.ax.set_ylabel(ylabel) #precisamos acessar o objeto ax dentro de cbar Cb = m.contour(stab,20,linewidths=2.0, colors='darkgreen', linestyles='-') # Adicione um título. plt.title(titulo) # Salve o arquivo plt.show() plt.savefig(salvar,dpi=500)
from mpl_toolkits.basemap import Basemap import numpy as np import matplotlib.pyplot as plt m = Basemap(projection='cea',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, y=7, 51 m.drawmapscale( x, y, x, y,500, barstyle='fancy' ) #plt.title("Equidistant Cylindrical Projection") #plt.show() plt.savefig('/home/s.von.hall/seminar/bspscalar.png')
# code to plot a point, used for verifying a new coordinate #pos_fidicual = m(-122.2436564, 37.813227) #dev = m.scatter( # pos_fidicual[0], pos_fidicual[1], # 5, marker='o', lw=.25, # facecolor='#33ccff', edgecolor='w', # alpha=0.9, antialiased=True, # label='Fiducial', zorder=3) # Draw a map scale if radius < 2 : scaleLen = round(radius*4)/8*1000 else : scaleLen = round(radius/2)*1000 m.drawmapscale( coords[0] + w*0.2, coords[1] + h * 0.05, # width was 0.8 before coords[0], coords[1], int(scaleLen), # length, in m barstyle='fancy', labelstyle='simple', units = 'm', fillcolor1='w', fillcolor2='#555555', fontcolor='#555555', zorder=4) # previously was 4 plt.title("Oakland housing development, 1895-2015") plt.tight_layout() # this will set the image width to 722px at 100dpi fig.set_size_inches(7.22, 5.25) # use for larger size plt.savefig('data/Oakland_temp.png', dpi=300, alpha=True) plt.show()
m = Basemap(projection='lcc',resolution='i',\ lon_0=lonLS,lat_0=latLS,\ width=Lx,height=Ly) m.drawcoastlines() m.fillcontinents(color='gray') m.drawparallels(np.arange(-60, 70, stride), labels=[1, 0, 0, 0], linewidth=0, fontsize=fs) m.drawmeridians(np.arange(-100, 100, stride), labels=[0, 0, 0, 1], linewidth=0, fontsize=fs) m.drawmapscale(m.lonmin+0.5*(m.lonmax-m.lonmin),\ m.latmin+0.075*(m.latmax-m.latmin),\ lonLS,latLS,scaleunit,units='km',\ barstyle='fancy',yoffset=0.015*(m.ymax-m.ymin),fontsize=fs-2) xr, yr = m(simul.x, simul.y) m.plot(lonLS, latLS, symbol, color='yellow', markersize=ms, latlon=True) ctf = m.contourf(xr, yr, simul.topo, levels=levels_bck, cmap=cmap_bck, extend='max') #for pc in ctf.collections: pc.set_rasterized(True) scat = m.scatter(plon[:], plat[:], c='r', s=ptsize, linewidths=ln, latlon=True) ax.tick_params(labelsize=fs)
# Preencha os continentes. A cor é em formato hexadecimal. mapa.fillcontinents(color='#BDA973'); # Adicione a linha de costa mapa.drawcoastlines(linewidth=1); # Adicine meridianos e paralenos na figura rotulo=[1,0,0,1]; mapa.drawmeridians(range(-180,180,10),labels=rotulo); mapa.drawparallels(range(-90,90,10),labels=rotulo); # Adicione os rios. Neste caso, a cor será branca. mapa.drawrivers(color='w'); # Adicione a escala. mapa.drawmapscale(-30,-3,-20,0,200, barstyle='fancy', units='km', labelstyle='simple',fontsize=12); # Adicione a batimetria. bLON,bLAT,BAT = download_bathy(lnd=lonmin,lnu=lonmax,ltd=latmin,ltu=latmax) # Salve os dados batimétricos. BDATA = dict(LON=bLON,LAT=bLAT,BAT=BAT) #save_pickle(BDATA,'/home/uesleisutil/Documentos/python_scripts/batimetria') # Use a paleta de cores do cmocean kw = dict(levels=range(-4500,0+100,100),cmap=cm.deep) Cf = mapa.contourf(bLON,bLAT,BAT,**kw); #o **kw colocará cada um dos argumentos dentro da função cbar = plt.colorbar(Cf); # Adicione a batimetria. Ct = plt.contour(bLON,bLAT,BAT,[-4000,-3000,-500,-10],colors='k')
def on_map(positions, scale=1e5, proj='cass'): """ The supported projections are: cea Cylindrical Equal Area mbtfpq McBryde-Thomas Flat-Polar Quartic aeqd Azimuthal Equidistant sinu Sinusoidal poly Polyconic omerc Oblique Mercator gnom Gnomonic moll Mollweide lcc Lambert Conformal tmerc Transverse Mercator nplaea North-Polar Lambert Azimuthal gall Gall Stereographic Cylindrical npaeqd North-Polar Azimuthal Equidistant mill Miller Cylindrical merc Mercator stere Stereographic eqdc Equidistant Conic rotpole Rotated Pole cyl Cylindrical Equidistant npstere North-Polar Stereographic spstere South-Polar Stereographic hammer Hammer geos Geostationary nsper Near-Sided Perspective eck4 Eckert IV aea Albers Equal Area kav7 Kavrayskiy VII spaeqd South-Polar Azimuthal Equidistant ortho Orthographic cass Cassini-Soldner vandg van der Grinten laea Lambert Azimuthal Equal Area splaea South-Polar Lambert Azimuthal robin Robinson :param positions: :param proj: projection type :param scale: :return: None """ # llcrnrlat,llcrnrlon,urcrnrlat,urcrnrlon # are the lat/lon values of the lower left and upper right corners # of the map. # resolution = 'i' means use intermediate resolution coastlines. # lon_0, lat_0 are the central longitude and latitude of the projection. # m = Basemap(llcrnrlon=-10.5,llcrnrlat=49.5,urcrnrlon=3.5,urcrnrlat=59.5, # resolution='i',projection=proj,lon_0=-4.36,lat_0=54.7) # can get the identical map this way (by specifying width and # height instead of lat/lon corners) lat, lon = [p[0] for p in positions], [p[1] for p in positions] pos = (sum(lat) / len(lat), sum(lon) / len(lon)) map_width = map_height = scale # optimized for the scale: 1e5 if map_width > 9e4: res = 'h' scale_untis, scale_factor = 'km', 1e4 else: res = 'c' scale_untis, scale_factor = 'm', 5 m = Basemap(width=map_width, height=map_height, resolution=res, # 'c', 'l', 'i', 'h', 'f' projection=proj, lon_0=pos[1], lat_0=pos[0]) m.drawcoastlines() m.fillcontinents(color='coral', lake_color='aqua') # draw parallels and meridians. m.drawparallels(np.arange(int(pos[0]) - 10, int(pos[0]) + 10, 1.), labels=[1, 0, 0, 1]) m.drawmeridians(np.arange(int(pos[1]) - 10, int(pos[1]) + 10, 1.), labels=[1, 0, 0, 1]) m.drawmapboundary(fill_color='aqua') m.plot(lon, lat, '.b--', zorder=10, latlon=True) cm = plt.cm.get_cmap('YlOrRd') colors = range(len(positions)) m.scatter(lon, lat, # longitude first! c=colors, cmap=cm, latlon=True, # lat and long in degrees zorder=11) # on top of all x0, y0 = m(pos[1], pos[0]) # center os the plot lon_lab, lat_lab = m(x0 + 0.4 * map_width, y0 - 0.4 * map_width, inverse=True) m.drawmapscale( lon_lab, lat_lab, # where to place scale pos[1], pos[0], # where to measure scale length=map_width / scale_factor, units=scale_untis, fontsize=10, barstyle='fancy', labelstyle='simple', fillcolor1='w', fillcolor2='#000000', fontcolor='#000000', zorder=20) m.drawmapscale(pos[1], pos[0], pos[0], pos[1], 10, barstyle='simple', fontsize=10, zorder=50) plt.title(u'Map centered at (%.1fN, %.1fE)' % pos) plt.colorbar() # draw inset with starting position # draw_inset(plt,m,pos,lat,lon) plt.show()
def plotMap(self, maxStationDistance=None, minStationDistance=None, saveFigs=False): """ Make plot of events (as beachball) and stations. Parameters ---------- maxDistance : float or int The maximum distance from an event for stations to plot """ ##Try to import basemap try: from mpl_toolkits.basemap import Basemap except ImportError: raise ImportError("mpl_toolskits does not have basemap, plotting cannot be perfromed") plt.figure() stadf, evedf = self._filterStationEvents( maxStationDistance=maxStationDistance, minStationDistance=minStationDistance ) stadfcur = stadf[[not x for x in stadf.Proposed]] stadfpro = stadf[[bool(x) for x in stadf.Proposed]] ## set up map basics latmin = min([evedf.LAT.min(), stadf.LAT.min()]) lonmin = min([evedf.LON.min(), stadf.LON.min()]) latmax = max([evedf.LAT.max(), stadf.LAT.max()]) lonmax = max([evedf.LON.max(), stadf.LON.max()]) latbuff = abs((latmax - latmin) * 0.1) # create buffers so there is a slight border with no events around map lonbuff = abs((lonmax - lonmin) * 0.1) totalxdist = ( obspy.core.util.geodetics.gps2DistAzimuth(latmin, lonmin, latmin, lonmax)[0] / 1000.0 ) # get the total x distance of plot in km # totalydist=obspy.core.util.geodetics.gps2DistAzimuth(latmin,lonmin,latmax,lonmin)[0]/1000. emap = Basemap( projection="merc", lat_0=np.mean([latmin, latmax]), lon_0=np.mean([lonmin, lonmax]), resolution="h", area_thresh=0.1, llcrnrlon=lonmin - lonbuff, llcrnrlat=latmin - latbuff, urcrnrlon=lonmax + lonbuff, urcrnrlat=latmax + latbuff, ) emap.drawmapscale(lonmin, latmin, lonmin, latmin, totalxdist / 4.5) # emap.drawrivers() xmax, xmin, ymax, ymin = emap.xmax, emap.xmin, emap.ymax, emap.ymin # horrange=max((xmax-xmin),(ymax-ymin)) #horizontal range x, y = emap(stadfcur.LON.values, stadfcur.LAT.values) emap.plot(x, y, "^", color="k", ms=6.0) x, y = emap(stadfpro.LON.values, stadfpro.LAT.values) emap.plot(x, y, "^", color="b", ms=6.0) x, y = emap(evedf.LON.values, evedf.LAT.values) emap.plot(x, y, ".", color="r", ms=7.0) emap.drawstates() for evenum, everow in evedf.iterrows(): x, y = emap(everow.LON, everow.LAT) txt = everow.NAME plt.annotate(txt, xy=(x, y), xycoords="data") latdi, londi = [ abs(latmax - latmin), abs(lonmax - lonmin), ] # get maximum degree distance for setting scalable ticks maxdeg = max(latdi, londi) parallels = np.arange(0.0, 80, maxdeg / 4) emap.drawparallels(parallels, labels=[1, 0, 0, 1], linewidth=0.0) meridians = np.arange(10.0, 360.0, maxdeg / 4) emap.drawmeridians(meridians, labels=[1, 0, 0, 1], rotation=90, linewidth=0.0) if saveFigs: plt.savefig("Map.pdf") else: plt.show()
ax = fig.add_subplot(111) m = Basemap(projection='merc',\ llcrnrlon=llcrnrlon,llcrnrlat=llcrnrlat, \ urcrnrlon=urcrnrlon,urcrnrlat=urcrnrlat,\ rsphere=6371200.,resolution='h',area_thresh=100) # draw coastlines, state and country boundaries, edge of map. m.drawcoastlines() m.drawstates() m.drawcountries() #m.drawmapboundary(fill_color='blue', zorder=50) #m.fillcontinents(color='coral',lake_color='aqua') m.drawparallels(arange(-90.,90.,0.5), labels=[1,0,0,0],fontsize=16, dashes=[2, 2], color='0.99', linewidth=0.0) m.drawmeridians(arange(0.,360.,0.5), labels=[0,0,0,1], fontsize=16, dashes=[2, 2], color='0.99', linewidth=0.0) m.drawmapscale(145.5, -39.2, 145.5, -39.2, 100, fontsize = 16, barstyle='fancy', zorder=100) ########################################################################################## # read topo ########################################################################################## mdiv = 500. if getcwd().startswith('/nas'): netcdffile = 'topo/srtm_66_20.grd' else: netcdffile = '//Users//trev//Documents//DATA//SRTM03//victoria_srtm03.grd' nc = NetCDFFile(netcdffile) zscale = 5. #colour data = nc.variables['z'][:] / zscale lons = nc.variables['x'][:] lats = nc.variables['y'][:]
cmap = plt.get_cmap('Blues') # draw wards with grey outlines df_map['patches'] = df_map['poly'].map(lambda x: PolygonPatch(x, ec='#555555', lw=.2, alpha=1., zorder=4)) pc = PatchCollection(df_map['patches'], match_original=True) # impose our colour map onto the patch collection norm = Normalize() color_map = cmap(norm(df_map['jenks_bins'].values)) to_modify = pd.DataFrame(color_map) to_modify.ix[df_map[df_map.postcode == 'EC1V 1'].index] = np.array([[1,1,0,1],[1,1,0,1],[1,1,0,1]]) pc.set_facecolor(np.array(to_modify)) ax.add_collection(pc) # Add a colour bar cb = colorbar_index(ncolors=len(jenks_labels), cmap=cmap, shrink=0.5, labels=jenks_labels) cb.ax.tick_params(labelsize=6) # Draw a map scale m.drawmapscale( bounds_dictionary['coords'][0] + 0.08, bounds_dictionary['coords'][1] + 0.015, bounds_dictionary['coords'][0], bounds_dictionary['coords'][1], 10., barstyle='fancy', labelstyle='simple', fillcolor1='w', fillcolor2='#555555', fontcolor='#555555', zorder=5) # this will set the image width to 722px at 100dpi plt.tight_layout() fig.set_size_inches(7.22, 5.25) plt.savefig('london_parking.png', dpi=500, alpha=True) plt.show()
ax.legend(loc=3, fontsize=14, markerscale=6) #m.drawmapboundary(fill_color='aqua') #m.fillcontinents(color='#cc9955', lake_color='aqua') m.drawcounties() # draw parallels. parallels = np.arange(30., 50, 0.5) m.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=14, linewidth=0.0, color='gray') # draw meridians meridians = np.arange(180., 360., 0.5) m.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=14, linewidth=0.0, color='gray') m.drawmapscale(-105.6, 40.7, origin[1], origin[0], 50, barstyle='fancy') plt.show(block=False) #plt.savefig('/data/iortega/Manuscripts/Tropgases/fig//Map.pdf', bbox_inches='tight', dpi=80) plt.savefig('/data/iortega/pbin/tropGases/fig/Map.pdf', bbox_inches='tight', dpi=80) user_input = raw_input('Press any key to exit >>> ') sys.exit()
# print lat # print map0(0,-60.) # map0 = Basemap(projection='spstere', lat_ts=-71, boundinglat=lat, lon_0=180, rsphere=(6378137.00,6356752.3142)) # urcrnrlon,urcrnrlat=map0(6667000, 6667000, inverse=True) # print llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat # map0 = Basemap(projection='stere', lat_ts=-71, lat_0=-90, lon_0=180, llcrnrlat=llcrnrlat, llcrnrlon=llcrnrlon, urcrnrlat=urcrnrlat, urcrnrlon=urcrnrlon, rsphere=(6378137.00,6356752.3142)) map1 = Basemap(projection='stere', lat_ts=-71, lat_0=-90, lon_0=180, llcrnrlat=lat1, llcrnrlon=lon1, urcrnrlat=lat2, urcrnrlon=lon2, rsphere=(6378137.00,6356752.3142)) #map1 = Basemap(projection='spstere', boundinglat=-60, lon_0=180, llcrnrx=-4.5e6, llcrnry=-2.3e6, urcrnrx=-5e6, urcrnry=-2.8e6) #m = Basemap(projection='stere', lat_0=-75, lon_0=123., width=1e6, height=1e6) #m.drawcoastlines() #m.fillcontinents(color='white',lake_color='aqua') #m.drawmapboundary(fill_color='aqua') map1.drawparallels(np.arange(-90.,81.,lat_step), labels=[True, False, False, True], dashes=[1, 5], color='0.5') map1.drawmeridians(np.arange(-180.,180.,lon_step), latmax=85., labels=[False, True, True, False], dashes=[1, 5], color='0.5') map1.drawmapscale(lon1-1.2, lat1+0.2, lon1, lat1, 20, yoffset=10., barstyle='simple') ##Draw bed topography #raster = gdal.Open('bedmap2/bedmap2_bed.txt') #band = raster.GetRasterBand(1) #array = band.ReadAsArray() #array=np.where(array==-9999,np.nan,array) #map1.imshow(array[::-1,:]) #map1.colorbar() ##Draw surface contours raster2 = gdal.Open(RLDir+'bedmap2/bedmap2_surface.txt')
from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt #-- mp = Basemap(projection='lcc', lat_0=39.73, lon_0=-89.5, width=350000, height=625000, resolution='h') mp.drawcounties() mp.etopo() mp.drawcoastlines(linewidth=1.5) mp.drawrivers(color='cyan', linewidth=1.25) mp.drawstates(zorder=20, linewidth=1.5) mp.drawmapscale(-90.75, 37.5, -90.75, 37.5, 100, barstyle='fancy', zorder=100, fontsize=10) plt.title('Map of Illinois', fontsize=16) fig = plt.gcf() fig.set_size_inches((8.5, 11)) plt.show() fig.savefig('map_ill.png', dpi=100) #--
font = matplotlib.font_manager.FontProperties(size = 18) text.set_font_properties(font) # Mark location of tower point_x, point_y = map(tower_lon, tower_lat) map.plot(point_x, point_y, marker = 's', color = 'black', markersize = 8) plt.text(point_x + 250, point_y - 80, 'Tower', fontsize = 18) # Create north arrow arrow_lon = easternmost_lon - abs(westernmost_lon - easternmost_lon) / 12 arrow_lat = northernmost_lat - abs(northernmost_lat - southernmost_lat) / 15 arrow_x, arrow_y = map(arrow_lon, arrow_lat) text_x, text_y = (0, -120) plt.annotate('$N$', xy = (arrow_x, arrow_y), xycoords = 'data', xytext = (text_x, text_y), textcoords = 'offset points', color='black', fontsize = 24, verticalalignment = 'center', horizontalalignment = 'center', arrowprops = dict(shrink = 0.05, width = 0.5, color = 'black')) # Draw scale bar scale_bar_lon_loc = westernmost_lon + abs(westernmost_lon - easternmost_lon) / 5 scale_bar_lat_loc = southernmost_lat + abs(northernmost_lat - southernmost_lat) / 10 map.drawmapscale(scale_bar_lon_loc, scale_bar_lat_loc, tower_lon, tower_lat, 2000, units = 'm', fontsize = 12, barstyle = 'fancy') plt.show()
labels=[0, 0, 0, 1], fontsize=16, dashes=[2, 2], color='0.5', linewidth=0.75) # get scale position and length slon = m.llcrnrlon + 0.26 * (m.urcrnrlon - m.llcrnrlon) slat = m.llcrnrlat + 0.93 * (m.urcrnrlat - m.llcrnrlat) slon0 = mean([m.urcrnrlon, m.llcrnrlon]) slat0 = mean([m.urcrnrlat, m.llcrnrlat]) scaleLength = 400. m.drawmapscale(slon, slat, slon0, slat0, scaleLength, fontsize=14, barstyle='fancy', zorder=1000) ########################################################################################## # plot gebco ########################################################################################## print('Reading netCDF file...') nc = NetCDFFile( '//Users//trev//Documents//DATA//GMT//GEBCO//se_aus_gebco2014.nc') zscale = 20. #gray zscale = 30. #colour data = nc.variables['z'][:] / zscale
def plot(self, **kargs): bathy = kargs.get("bathy", "contourf") hvals = kargs.get("hvals", "auto") resolution = kargs.get("res", "i") rivers = kargs.get("rivers", False) parallels = kargs.get("parallels", "auto") meridians = kargs.get("meridians", "auto") scale = kargs.get("scale", False) states = kargs.get("states", False) xlim = kargs.get("xlim", False) ylim = kargs.get("ylim", False) title = kargs.get("title", "auto") cmap = kargs.get("cmap", pylab.cm.gist_earth_r) proj = kargs.get("proj", "merc") ax = kargs.get("ax", False) if not ax: fig = pylab.figure() ax = pylab.axes() else: fig = ax.figure h = np.ma.masked_where(self.mask == 0, self.h) xb, yb = self.border() xt = ticks.loose_label(self.lon.min(), self.lon.max()) yt = ticks.loose_label(self.lat.min(), self.lat.max()) ht = ticks.loose_label_n(self.h.min(), self.h.max(), 7) if xlim: Lonlims = xlim else: Lonlims = xt[0], xt[-1] if ylim: Latlims = ylim else: Latlims = yt[0], yt[-1] if hvals == "auto": hvals = ht if parallels == "auto": parallels = yt if meridians == "auto": meridians = xt if Basemap and proj: m = Basemap( projection=proj, lat_ts=0.0, # lon_0=self.lon[0].mean(), resolution=resolution, urcrnrlon=Lonlims[1], urcrnrlat=Latlims[1], llcrnrlon=Lonlims[0], llcrnrlat=Latlims[0], ) m.drawcoastlines(ax=ax) m.fillcontinents(ax=ax, color=(0.7604, 1.0000, 0.7459)) if rivers: m.drawrivers(color="b") m.drawcountries(ax=ax) # m.drawlsmask() # m.drawmapboundary() if scale: dx = Lonlims[1] - Lonlims[0] dy = Latlims[1] - Latlims[0] lon = Lonlims[1] - dx / 10 lat = Latlims[0] + dy / 10 lon0 = lon lat0 = lat length = 100 m.drawmapscale(lon, lat, lon0, lat0, length, ax=ax) if states: m.drawstates(ax=ax) m.drawparallels(parallels, labels=[1, 0, 0, 0], ax=ax) m.drawmeridians(meridians, labels=[0, 0, 0, 1], ax=ax) x, y = m(self.lon, self.lat) pch = False if bathy in ["pcolor", "pcolormesh"]: pch = ax.pcolormesh(x, y, h, cmap=cmap) elif bathy == "contour": pch = ax.contour(x, y, h, hvals, cmap=cmap) elif bathy == "contourf": pch = ax.contourf(x, y, h, hvals, cmap=cmap) if pch: if m.xmax - m.xmin < m.ymax - m.ymin: orientation = "horizontal" else: orientation = "vetical" cbh = pylab.colorbar(pch, orientation=orientation, ax=ax) cbh.set_label("Depth") if title == "auto": ax.set_title(self.name) elif title: ax.set_title(title) xb, yb = m(xb, yb) ax.plot(xb, yb) ax.axis([m.xmin, m.xmax, m.ymin, m.ymax]) return m else: ax.pcolormesh(self.lon, self.lat, h, cmap=cmap) ax.contour(self.lon, self.lat, self.h, hvals, colors="w") ax.plot(xb, yb)
x, y = m(lons, lats) m.scatter(x, y, s=50, marker='o', c='red', cmap=cm.cool, alpha=0.7, zorder=100.) m.drawmapscale(-43., -32., -47.1, -28.1, 1000, fontsize=10, zorder=5, barstyle='fancy') parallels = np.arange(-50., 10, 5.) print parallels m.drawparallels(parallels, labels=[1, 0, 0, 1]) meridians = np.arange(70., 360., 5.) print meridians m.drawmeridians(meridians, labels=[1, 0, 0, 1]) plt.show()
def checkComCat(rtable, ftable, cnum, f, startTime, windowStart, opt): """ Checks repeater trigger times with projected arrival times from ANSS Comprehensive Earthquake Catalog (ComCat) and writes these to HTML and image files. Will also check NCEDC catalog if location is near Northern California. rtable: Repeater table ftable: Families table cnum: cluster number to check f: HTML file to write to startTime: startTime column from rtable (convenience) windowStart: windowStart column from rtable (convenience) opt: Options object describing station/run parameters Traces through iasp91 global velocity model; checks for local, regional, and teleseismic matches for limited set of phase arrivals """ pc = ['Potential', 'Conflicting'] model = TauPyModel(model="iasp91") mc = 0 n = 0 l = 0 stalats = np.array(opt.stalats.split(',')).astype(float) stalons = np.array(opt.stalons.split(',')).astype(float) latc = np.mean(stalats) lonc = np.mean(stalons) members = np.fromstring(ftable[cnum]['members'], dtype=int, sep=' ') order = np.argsort(startTime[members]) f.write('</br><b>ComCat matches:</b></br>') for m in members[order]: t = UTCDateTime(startTime[m]) + windowStart[m] / opt.samprate cc_url = ('http://earthquake.usgs.gov/fdsnws/event/1/query?' 'starttime={}&endtime={}&format=text').format( t - 1800, t + 30) try: comcat = pd.read_csv(cc_url, delimiter='|') otime = comcat['Time'].tolist() lat = comcat['Latitude'].tolist() lon = comcat['Longitude'].tolist() dep = comcat['Depth/km'].tolist() mag = comcat['Magnitude'].tolist() place = comcat['EventLocationName'].tolist() except urllib2.HTTPError: otime = [] lat = [] lon = [] dep = [] mag = [] place = [] # Check if near Northern California, then go to NCEDC for additional events but # for shorter time interval if latc > 34 and latc < 42 and lonc > -124 and lonc < -116: cc_urlnc = ('http://ncedc.org/fdsnws/event/1/query?' 'starttime={}&endtime={}&format=text').format( (t - 60).isoformat(), (t + 30).isoformat()) try: ncedc = pd.read_csv(cc_urlnc, delimiter='|') otime.extend(ncedc[' Time '].tolist()) lat.extend(ncedc[' Latitude '].tolist()) lon.extend(ncedc[' Longitude '].tolist()) dep.extend(ncedc[' Depth/km '].tolist()) mag.extend(ncedc[' Magnitude '].tolist()) place.extend(ncedc[' EventLocationName'].tolist()) except ValueError: pass n0 = 0 for c in range(len(otime)): deg = locations2degrees(lat[c], lon[c], latc, lonc) dt = t - UTCDateTime(otime[c]) if deg <= opt.locdeg: mc += 1 if np.remainder(mc, 100) == 0: model = TauPyModel(model="iasp91") arrivals = model.get_travel_times( source_depth_in_km=max(0, dep[c]), distance_in_degree=deg, phase_list=['p', 's', 'P', 'S']) if len(arrivals) > 0: pt = np.zeros((len(arrivals), )) pname = [] for a in range(len(arrivals)): pt[a] = arrivals[a].time - dt pname.append(arrivals[a].name) if np.min(abs(pt)) < opt.serr: amin = np.argmin(abs(pt)) f.write( ('{} local match: {} ({}, {}) {}km M{} {} - ({}) ' '{:4.2f} s</br>').format(pc[n0], otime[c], lat[c], lon[c], dep[c], mag[c], place[c], pname[amin], pt[amin])) n0 = 1 l = l + 1 if l == 1: llats = np.array(lat[c]) llons = np.array(lon[c]) ldeps = np.array(dep[c]) else: llats = np.append(llats, lat[c]) llons = np.append(llons, lon[c]) ldeps = np.append(ldeps, dep[c]) elif deg <= opt.regdeg and mag[c] >= opt.regmag: mc += 1 if np.remainder(mc, 100) == 0: model = TauPyModel(model="iasp91") arrivals = model.get_travel_times( source_depth_in_km=max(0, dep[c]), distance_in_degree=deg, phase_list=['p', 's', 'P', 'S', 'PP', 'SS']) if len(arrivals) > 0: pt = np.zeros((len(arrivals), )) pname = [] for a in range(len(arrivals)): pt[a] = arrivals[a].time - dt pname.append(arrivals[a].name) if np.min(abs(pt)) < opt.serr: amin = np.argmin(abs(pt)) f.write(( '{} regional match: {} ({}, {}) {}km M{} {} - ({}) ' '{:4.2f} s</br>').format(pc[n0], otime[c], lat[c], lon[c], dep[c], mag[c], place[c], pname[amin], pt[amin])) n0 = 1 elif deg > opt.regdeg and mag[c] >= opt.telemag: mc += 1 if np.remainder(mc, 100) == 0: model = TauPyModel(model="iasp91") arrivals = model.get_travel_times( source_depth_in_km=max(0, dep[c]), distance_in_degree=deg, phase_list=[ 'P', 'S', 'PP', 'SS', 'PcP', 'ScS', 'PKiKP', 'PKIKP' ]) if len(arrivals) > 0: pt = np.zeros((len(arrivals), )) pname = [] for a in range(len(arrivals)): pt[a] = arrivals[a].time - dt pname.append(arrivals[a].name) if np.min(abs(pt)) < opt.serr: amin = np.argmin(abs(pt)) f.write(( '{} teleseismic match: {} ({}, {}) {}km M{} {} - ({}) ' '{:4.2f} s</br>').format(pc[n0], otime[c], lat[c], lon[c], dep[c], mag[c], place[c], pname[amin], pt[amin])) n0 = 1 if n0 > 1: n = n + 1 else: n = n + n0 if n > 0: f.write('Total potential matches: {}</br>'.format(n)) f.write('Potential local matches: {}</br>'.format(l)) if l > 0: m = Basemap(llcrnrlon=lonc - 2 * opt.locdeg, llcrnrlat=latc - opt.locdeg, urcrnrlon=lonc + 2 * opt.locdeg, urcrnrlat=latc + opt.locdeg, resolution='l', projection='tmerc', lon_0=lonc, lat_0=latc) m.scatter(llons, llats, s=5, alpha=0.5, marker='o', color='r', latlon=True) m.scatter(stalons, stalats, marker='^', color='k', facecolors='None', latlon=True) m.drawparallels(np.arange(np.floor(latc - opt.locdeg), np.ceil(latc + opt.locdeg), opt.locdeg / 2), labels=[1, 0, 0, 0]) m.drawmeridians(np.arange(np.floor(lonc - 2 * opt.locdeg), np.ceil(lonc + 2 * opt.locdeg), opt.locdeg), labels=[0, 0, 0, 1]) m.drawmapscale(lonc - opt.locdeg - 0.1, latc - opt.locdeg + 0.1, lonc, latc, length=50, barstyle='fancy') plt.title('{} potential local matches (~{:3.1f} km depth)'.format( l, np.mean(ldeps))) plt.savefig('./{}/clusters/map{}.png'.format(opt.groupName, cnum), dpi=100) plt.close() f.write('<img src="map{}.png"></br>'.format(cnum)) else: f.write('No matches found</br>')
axes[1].set_title("Inner-core wind structure", fontweight='bold') my_map1 = Basemap(projection='gall',llcrnrlat=-90,urcrnrlat=90,llcrnrlon=-360,urcrnrlon=0,ax=axes[1]) xmap,ymap = my_map1(x, y) fig1 = my_map1.scatter(xmap, ymap, s=5, c=rmax, alpha=0.75,lw = 0, cmap=plt.cm.OrRd, vmin=0, vmax=100) #my_map1.drawmapboundary(fill_color='blue') my_map1.fillcontinents(color='lightgreen',lake_color='lightgreen') my_map1.drawcoastlines() my_map1.drawmeridians(np.arange(0, 360, 60),labels=[1,1,0,1]) my_map1.drawparallels(np.arange(-90, 90, 30),labels=[1,0,0,1]) cb = my_map1.colorbar(fig1, extend='max') cb.set_label('radius of maximum winds (RMW) [km]') axes[2].set_title("Outer wind structure", fontweight='bold') my_map2 = Basemap(projection='gall',llcrnrlat=-90,urcrnrlat=90,llcrnrlon=-360,urcrnrlon=0,ax=axes[2]) xmap,ymap = my_map2(xr35, yr35) fig2 = my_map2.scatter(xmap, ymap, s=5, c=r35, alpha=0.75,lw = 0, cmap=plt.cm.YlOrRd, vmin=0, vmax=250) #my_map2.drawmapboundary(fill_color='blue') my_map2.fillcontinents(color='lightgreen',lake_color='lightgreen') my_map2.drawcoastlines() my_map2.drawmeridians(np.arange(0, 360, 60),labels=[1,1,0,1]) my_map2.drawparallels(np.arange(-90, 90, 30),labels=[1,0,0,1]) cb = my_map2.colorbar(fig2, extend='max') cb.set_label('average difference radius of 35 knots [km]') my_map2.drawmapscale(-90, -80, -90, -80, 5000, barstyle='simple', units='km', fontsize=9, yoffset=None, labelstyle='simple', fontcolor='k', fillcolor1='w', fillcolor2='k', ax=None, format='%d', zorder=None) plt.show() fnamefig = 'world2.png' plt.savefig(fnamefig, dpi=300) plt.close('all')
k, ha='center', va='center', size=6, color='black') #pos_fidicual = m(-122.2436564, 37.813227) #dev = m.scatter( # pos_fidicual[0], pos_fidicual[1], # 5, marker='o', lw=.25, # facecolor='#33ccff', edgecolor='w', # alpha=0.9, antialiased=True, # label='Fiducial', zorder=3) # Draw a map scale m.drawmapscale( coords[0] + w*0.8, coords[1] + h * 0.05, coords[0], coords[1], 1000*radius/2, # length, in m barstyle='fancy', labelstyle='simple', units = 'm', # format='%.2f', fillcolor1='w', fillcolor2='#555555', fontcolor='#555555', zorder=4) plt.title("Arbor Villa development, 1926-1935") plt.tight_layout() # this will set the image width to 722px at 100dpi fig.set_size_inches(7.22, 5.25) # use for larger size #fig.set_size_inches(3.5, 2.5) plt.savefig('data/Oakland_temp.png', dpi=300, alpha=True) plt.show()
class Map(object): def __init__( self, shp_file_path, region, left_blank=0.1, right_blank=0.1, upper_blank=0.1, lower_blank=0.1, projection='cyl', **kwargs, ): """ 创建地图, 用于绘图的空间,将生成的 Basemap 对象 map 以及各参数绑定到 Map 类上面 :param shp_file_path: str -> 要打开的 shapefile 文件 :param region: str or int -> 地区名 或 地区编码 会检索 shp file infos 的所有 record 进行匹配, 因此, 需保证此值唯一性, 否则将获取拥有此值的最后一个元素 :param left_blank: float -> 左空白,占整个绘图区域宽度的比例 :param right_blank: float -> 右空白,占整个绘图区域宽度的比例 :param upper_blank: float -> 上空白,占整个绘图区域宽度的比例 :param lower_blank: float -> 下空白,占整个绘图区域宽度的比例 :param projection: str -> 地图成图投影方式 同 Basemap 类 :param kwargs: 创建 Basemap 对象实例的其他参数 """ self.shp_file_path = shp_file_path self.region = region self.right_blank = right_blank self.left_blank = left_blank self.upper_blank = upper_blank self.lower_blank = lower_blank self.max_lon = 180 self.min_lon = 0 self.max_lat = 90 self.min_lat = -90 if not os.path.exists(shp_file_path): pass else: self.shp_file = shapefile.Reader(shp_file_path) for shape_record in self.shp_file.shapeRecords(): if str(region) in shape_record.record: points = shape_record.shape.points self.lons, self.lats = zip(*points) self.max_lon = max(self.lons) self.max_lat = max(self.lats) self.min_lon = min(self.lons) self.min_lat = min(self.lats) axes_x_length = (self.max_lon - self.min_lon) / (1 - (left_blank + right_blank)) axes_y_length = (self.max_lat - self.min_lat) / (1 - (upper_blank + lower_blank)) self.llcrnrlon = self.min_lon - axes_x_length * left_blank self.llcrnrlat = self.min_lat - axes_y_length * lower_blank self.urcrnrlon = self.max_lon + axes_x_length * right_blank self.urcrnrlat = self.max_lat + axes_y_length * upper_blank self.lon_0 = (self.min_lon + self.max_lon) / 2 self.lat_0 = (self.min_lat + self.max_lat) / 2 self.paint_area = { 'lon_0': self.lon_0, 'lat_0': self.lat_0, 'llcrnrlon': self.llcrnrlon, 'llcrnrlat': self.llcrnrlat, 'urcrnrlon': self.urcrnrlon, 'urcrnrlat': self.urcrnrlat, } self.map = Basemap(**self.paint_area, projection=projection, **kwargs) def draw_scale(self, length_offset_times=0.25, yoffset_times=None, barstyle='fancy', **kwargs): """ 绘制比例尺, 非等距投影无法绘制比例尺,建议绘制经纬网 :param length_offset_times: float -> 长度比例 :param yoffset_times: float -> 长宽比, 默认0.02 :param kwargs: float -> 其他参数 :param barstyle: str -> 比例尺样式 :return: 无返回值 """ lon = (self.max_lon + self.min_lon) / 2 lat = (self.min_lat + self.llcrnrlat) / 2 lon_0 = self.lon_0 lat_0 = self.lat_0 l_x, l_y = self.map(self.llcrnrlon, self.llcrnrlat) u_x, u_y = self.map(self.urcrnrlon, self.urcrnrlat) for _x in [10**i for i in range(-3, 9)]: real_length = (u_x - l_x) / 1000 * length_offset_times if (real_length > _x / 10) and (real_length < _x): length = math.ceil((u_x - l_x) / 1000 * length_offset_times / (_x / 10)) * (_x / 10) if not yoffset_times is None: yoffset = (u_y - l_y) * yoffset_times else: yoffset = None self.map.drawmapscale(lon, lat, lon_0, lat_0, length, yoffset=yoffset, barstyle=barstyle, **kwargs) def draw_colorbar(self): pass def draw_lon_lat_lines(self, lon_line_num=7, lat_line_num=7, ratio=True): lon_width = self.urcrnrlon - self.llcrnrlon lat_width = self.urcrnrlat - self.llcrnrlat if ratio == True: if lon_width > lat_width: lat_line_num = int(lon_line_num * lat_width / lon_width) + 1 else: lon_line_num = int(lat_line_num * lon_width / lat_width) + 1 meridians = np.linspace(self.min_lon, self.max_lon, lon_line_num) parallels = np.linspace(self.min_lat, self.max_lat, lat_line_num) # 绘制经度线 self.map.drawmeridians(meridians, labels=[0, 0, 1, 1], fontsize=10, fmt='%.2f', dashes=[1, 4], color='gray') # 绘制纬度线 self.map.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=10, fmt='%.2f', dashes=[1, 4], color='gray') return [meridians, parallels] def draw_region_name(self, shp_file_name=None, region_name=None): shp = shapefile.Reader(shp_file_name) for shape_record in shp.shapeRecords(): if region_name in shape_record.record: lon, lat = shape_record.shape.points[0] x, y = self.map(lon, lat) self.map.scatter(x, y, s=100, color='r', marker='*') return [x, y]
def makemap(edilist,mapstretchfactor,symbolsize,labelsize,showlabel): #import of modules here due to warnings from Matplotlib packages #these warnings distract the 'usage' information from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt import matplotlib as mpl import mtpy.utils.filehandling as MTfh import mtpy.core.edi as EDI import mtpy.utils.filehandling as MTfh lats = [] lons =[] names=[] for i in edilist: e = EDI.Edi() e.readfile(i) lats.append(e.lat) lons.append(e.lon) names.append(e.head['dataid'].lower()) coords = zeros((len(edilist),2)) coords[:,0] = lats coords[:,1] = lons latrange = max(lats) - min(lats) lonrange = max(lons) - min(lons) #center point for projection: c = [mean(lats),mean(lons)] #----------------------- #Matplotlib options mpl.rcParams['font.size'] = 10. mpl.rcParams['axes.labelsize'] = 8. mpl.rcParams['xtick.labelsize'] = 6. mpl.rcParams['ytick.labelsize'] = 6. plt.close('all') fig = plt.figure()#figsize=(5.7,4.3)) plt.subplots_adjust(left=0.2,right=0.9,top=0.90,bottom=0.1,wspace=0.15,hspace=0.05) ax = plt.subplot(111) stretch = float(mapstretchfactor) total_latmin = min(lats)-stretch*latrange total_lonmin = min(lons)-stretch*lonrange total_latmax = max(lats)+stretch*latrange total_lonmax = max(lons)+stretch*lonrange total_latrange = total_latmax - total_latmin total_lonrange = total_lonmax - total_lonmin #determine number of axes labels: maximumlabels = 5 latnum=maximumlabels lonnum=maximumlabels lonlat_stretch = total_lonrange/total_latrange if int(lonlat_stretch) > 2: #significantly more long than lat factor = int(int(lonlat_stretch)/2.) latnum = int(maximumlabels/factor) + 1 lonnum = maximumlabels elif int(lonlat_stretch) <0.5 : #significantly more long than lat factor = int(int(1./lonlat_stretch)/2.) lonnum = int(maximumlabels/factor) + 1 latnum = maximumlabels m = Basemap( projection='merc', lon_0=c[1],lat_0=c[0],lat_ts=c[0], llcrnrlat=total_latmin, urcrnrlat=total_latmax, llcrnrlon=total_lonmin, urcrnrlon=total_lonmax, rsphere=6371200.,resolution='h',ax=ax) lons.append(total_lonmin) lons.append(total_lonmax) lats.append(total_latmin) lats.append(total_latmax) xgrid, ygrid = m(*meshgrid(lons,lats)) xdiff = xgrid.max()-xgrid.min() ydiff = ygrid.max()-ygrid.min() largest_extent = max(ydiff,xdiff) m.drawcoastlines(linewidth=0.25,ax=ax) m.drawcountries(linewidth=0.25,ax=ax) m.fillcontinents(color='coral',lake_color='aqua',ax=ax) m.drawmapboundary(fill_color='aqua',ax=ax) m.drawparallels( [round(i,3) for i in linspace(total_latmin,total_latmax,latnum+1,False)][1:], labels=[1,0,0,0], fmt='%.1f' ) m.drawmeridians( [round(i,3) for i in linspace(total_lonmin,total_lonmax,lonnum+1,False)][1:], labels=[0,0,0,1], fmt='%.1f' ) m.drawrivers() m.etopo() m.drawmapscale( total_lonmax-0.15*total_lonrange, total_latmax-0.2*total_latrange, c[1],c[0], 2*10**(int(log10(largest_extent/1000.))-1), barstyle='simple', labelstyle='simple',fontsize=12, fontcolor='k', fillcolor1='r', fillcolor2='g', ax=None, format='%d', ) for x,y,name in zip(xgrid[0,:], ygrid[:,0],names): plt.plot(x,y,'v',ms=symbolsize,color='k',label=name) if showlabel is True: plt.text(x,y,name,fontsize=labelsize,ha='center',va='bottom',color='k',backgroundcolor='r')#, labelfontsize=5) plt.title('locations of {0} MT stations'.format(len(names))) f1 = 'station_locations_map.png' f2 = 'station_locations_map.svg' f1 = MTfh.make_unique_filename(f1) f2 = MTfh.make_unique_filename(f2) plt.savefig(f1,format='png',dpi=200) plt.savefig(f2,format='svg',transparent=True) return op.abspath(f1),op.abspath(f2)
# Topography xg, yg = map(lon_geo, lat_geo) th = map.contour(xg, yg, hgt, 6, colors='k') # Equipotential lines from 'HGT' # TKE as a contour-surface plot cs = map.contourf(x, y, tke, cmap='YlOrRd') # Wind barbs # Wind barbs xx = np.arange(0, len(x), 2) # Numpy arange (start, stop, step) yy = np.arange(0, len(y), 2) points = np.meshgrid(xx, yy) WindField = np.sqrt(u*u + v*v) map.barbs(x[points], y[points], u[points], v[points], barbcolor='b') # Rieppi coordinates Rlon, Rlat = map(20.6804, 69.1867) # ------ FIGURE -------- map.plot(Rlon, Rlat, 'go', markersize=8) cb = map.colorbar(cs, 'right', size='5%', pad='5%') cb.ax.tick_params(labelsize=font) map.drawmapscale(20.3, 68.98, 20.6804, 69.1867, 20, barstyle='fancy', fontsize=font) cb.set_label('TKE [m$^2$/s$^2$]', rotation=270, fontsize=font) plt.title('Domain 3, 10.12.14, 12:00', fontsize=font) # plt.savefig('/home/blasterdalen/Figures/TKE_WindBarbs_10dec_v2.png', dpi=200, bbox_inches='tight')
def draw_market_map(ls_market_ids, directory, zoom = 12, delta_lng = 0.18, delta_lat = 0.10): ls_close_ids = [x[0] for market_id in ls_market_ids for x in dict_ls_close[market_id]] ls_outside_ids = list(set(ls_close_ids).difference(set(ls_market_ids))) ls_market_coordinates = [df_info.ix[x][['lat', 'lng']].tolist() for x in ls_market_ids] lat_ref = (np.max([x[0] for x in ls_market_coordinates]) +\ np.min([x[0] for x in ls_market_coordinates])) / 2 lng_ref = (np.max([x[1] for x in ls_market_coordinates]) +\ np.min([x[1] for x in ls_market_coordinates])) / 2 ls_outside_coordinates = [df_info.ix[x][['lat', 'lng']].tolist() for x in ls_outside_ids] ## todo: see how to get dist of X km? #zoom = 12 # defines how many tiles are collected (precision) #delta_lat = 0.10 # height 0.10 #delta_lng = 0.18 # width 0.18 adj_lng_c = 0 # -0.01 a, bbox = getImageCluster(lat_ref - delta_lat, # need 1/2 delta_lat lng_ref - delta_lng + adj_lng_c, # need 1/2 delta_lng delta_lat * 2, delta_lng * 2, zoom) fig = plt.figure(figsize=(10, 10)) ax = plt.subplot(111) m = Basemap( llcrnrlon=bbox[0], llcrnrlat=bbox[1], urcrnrlon=bbox[2], urcrnrlat=bbox[3], projection='merc', ax=ax) # display image composed of OSM times m.imshow(a, interpolation='lanczos', origin='upper') # convert coord (caution: inversion) for ls_gps_points, marker_c, marker in [[ls_market_coordinates, 'b', 'o'], [ls_outside_coordinates, 'r', 's']]: ls_points = [m(x[1], x[0]) for x in ls_gps_points] ax.scatter([point[0] for point in ls_points], [point[1] for point in ls_points], alpha = 0.8, s = 30, color = marker_c, marker = marker, zorder = 9) # add circles def radius_for_tissot(dist_km): return np.rad2deg(dist_km/6367.) for ls_gps_points, marker_c, radius in [[ls_market_coordinates, 'b', 3], [ls_outside_coordinates, 'r', 5]]: for lat_x, lng_x in ls_gps_points: m.tissot(lng_x, lat_x, radius_for_tissot(radius), 256, facecolor=marker_c, alpha=0.1, zorder = 8) # need to cut again (otherwise get whole loaded tiles displayed) xmin, ymin = m(lng_ref - delta_lng + adj_lng_c, lat_ref - delta_lat) xmax, ymax = m(lng_ref + delta_lng + adj_lng_c, lat_ref + delta_lat) ax.set_xlim((xmin, xmax)) ax.set_ylim((ymin, ymax)) plt.tight_layout() #plt.show() # add correct map scale (or try using tmerc?) xmin_deg, ymin_deg = m(xmin, ymin, inverse = True) xmax_deg, ymax_deg = m(xmax, ymax, inverse = True) dref = 3.0 lat0 = ymin_deg + 0.005 #0.012 distance=dref/np.cos(lat0*np.pi/180.) scale = m.drawmapscale(lon = xmin_deg + 0.02, lat = ymin_deg + 0.005, #0.012, lon0 = lng_ref, #m.llcrnrlon, lat0 = lat_ref, #m.llcrnrlat, barstyle = 'fancy', labelstyle = 'simple', length = distance, yoffset = 0.01*(m.ymax-m.ymin), format = '%.1f') scale[12].set_text(dref/2.0) scale[13].set_text(dref) nb_ids = len(ls_market_ids) subdir = 'maps_market_6_plus' if nb_ids < 6: subdir = 'maps_market_{:d}'.format(nb_ids) plt.savefig(os.path.join(path_dir_built_graphs, directory, '{:d}_{:s}_map.png'.format(nb_ids, ls_market_ids[0])), dpi=90, alpha=True, bbox_inches = 'tight') plt.close()
# -*- coding: utf-8 -*- """ Created on Wed Jun 12 20:33:16 2019 @author: Administrator """ from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt map = Basemap(llcrnrlon=-10.5, llcrnrlat=35, urcrnrlon=4., urcrnrlat=44., resolution='i', projection='tmerc', lat_0=39.5, lon_0=-3.25) map.drawmapboundary(fill_color='aqua') map.fillcontinents(color='#cc9955', lake_color='aqua') map.drawcoastlines() #lon, lat, lon0, lat0, length, barstyle='simple', units='km', fontsize=9, yoffset=None, labelstyle='simple', fontcolor='k', fillcolor1='w', fillcolor2='k', ax=None, format='%d', zorder=None, linecolor=None, linewidth=None map.drawmapscale(-7., 35.8, -3.25, 39.5, 500, barstyle='fancy') map.drawmapscale(-0., 35.8, -3.25, 39.5, 500, fontsize=14) plt.show()
# map with land/sea mask plotted fig = plt.figure() m = Basemap(projection='ortho',lon_0=lon_0,lat_0=lat_0,resolution=None) # land red, oceans blue. # lakes=True means plot inland lakes with ocean color. m.drawlsmask(land_color='red',ocean_color='blue', lakes=True) # draw parallels and meridians. m.drawparallels(np.arange(-90.,120.,30.)) m.drawmeridians(np.arange(0.,420.,60.)) m.drawmapboundary() plt.title('Orthographic Map Centered on Lon=%s, Lat=%s' % (lon_0,lat_0)) # map with continents drawn and filled. fig = plt.figure() m = Basemap(projection='ortho',lon_0=lon_0,lat_0=lat_0,resolution='l') m.drawcoastlines() m.fillcontinents(color='coral',lake_color='aqua') m.drawcountries() # draw parallels and meridians. m.drawparallels(np.arange(-90.,120.,30.)) m.drawmeridians(np.arange(0.,420.,60.)) m.drawmapboundary(fill_color='aqua') # add a map scale. length = 5000 x1,y1 = 0.3*m.xmax, 0.25*m.ymax lon1,lat1 = m(x1,y1,inverse=True) m.drawmapscale(lon1,lat1,lon1,lat1,length,fontsize=8,barstyle='fancy',\ labelstyle='fancy',units='km') plt.title('Orthographic Map Centered on Lon=%s, Lat=%s' % (lon_0,lat_0)) plt.show()
def plot_target(data_temp, var_temp, start_indices_temp, end_indices_temp, out_dir_temp): #Set some strings if var_temp == 'rad_continuum_o2': var_string = 'o2_radiance' var_cbar_string = 'Radiance [Ph s' + r'$^{-1}$' + ' m' + r'$^{-2}$' + ' sr' + r'$^{-1}$' + r'$\mu$' + 'm' + r'$^{-1}$' + ']' var_title_string = "O" + r'$_2$' + ' A-Band Radiance' var_cbar = plt.cm.Purples_r elif var_temp == 'xco2': var_string = 'xco2' var_cbar_string = r'$X_{CO_2}$' + ' [ppm]' var_title_string = r'$X_{CO_2}$' var_cbar = plt.cm.viridis elif var_temp == 'dp': var_string = 'dp' var_cbar_string = 'dp [hPa]' var_title_string = 'dp' var_cbar = plt.cm.RdBu_r elif var_temp == 'aod_total': var_string = 'aod' var_cbar_string = 'AOD' var_title_string = 'AOD' var_cbar = plt.cm.magma else: print("Please select an appropriate variable...") ############################################ #Plot all the individual TG/AMs! for i in range(len(start_indices_temp)): print( "---------------------------------------------------------------") print("Plotting TG/AM ", str(i + 1), " of ", len(start_indices_temp)) data_temp2 = data_temp[start_indices_temp[i]:end_indices_temp[i]] print(data_temp2['target_id'][0], int(data_temp2['orbit'][0]), data_temp2['sounding_id'][0]) #Remove weird outliers that are far from the actual TG/AM cluster_input = np.array( [data_temp2['longitude'], data_temp2['latitude']]).T try: clusters = hcluster.fclusterdata(cluster_input, 1., criterion='distance') print("Cluster #s = ", np.bincount(clusters)) #Grab the largest cluster, or any/all clusters greater than 30 soundings cluster_mask = (clusters == np.argmax( np.bincount(clusters))) | np.isin( clusters, np.where(np.bincount(clusters) > 30)[0]) except: #If there's exactly one sounding, fclusterdata doesn't work cluster_mask = np.ones(len(data_temp2), dtype=bool) #Determine plotting box N,S,E,W = np.round(max(data_temp2['target_lat'][cluster_mask][0],data_temp2['latitude'][cluster_mask].max())+.25,1),\ np.round(min(data_temp2['target_lat'][cluster_mask][0],data_temp2['latitude'][cluster_mask].min())-.25,1),\ np.round(max(data_temp2['target_lon'][cluster_mask][0],data_temp2['longitude'][cluster_mask].max())+(.25/np.cos(np.deg2rad(max(data_temp2['target_lat'][cluster_mask][0],data_temp2['latitude'][cluster_mask].max())))),1),\ np.round(min(data_temp2['target_lon'][cluster_mask][0],data_temp2['longitude'][cluster_mask].min())-(.25/np.cos(np.deg2rad(min(data_temp2['target_lat'][cluster_mask][0],data_temp2['latitude'][cluster_mask].min())))),1) #And keep anything within the plotting box data_temp2 = data_temp2[(data_temp2['latitude'] < N) & (data_temp2['latitude'] > S) & (data_temp2['longitude'] < E) & (data_temp2['longitude'] > W)] #Get some datetime info from the sounding_id month_str = calendar.month_abbr[int( data_temp2['sounding_id'][0].astype(str)[4:6].lstrip("0"))] day_str, year_str = data_temp2['sounding_id'][0].astype( str)[6:8].lstrip("0"), data_temp2['sounding_id'][0].astype( str)[:4].lstrip("0") hour_str, minute_str = data_temp2['sounding_id'][0].astype( str)[8:10], data_temp2['sounding_id'][0].astype(str)[10:12] #Check if the .png exists already. If not, make it! if os.path.isfile(out_dir_temp + '/' + data_temp2['production_string'][0].astype(str) + '/' + var_string + '/OCO3_' + data_temp2['production_string'][0].astype(str) + "_" + var_string + '_' + str(data_temp2['sounding_id'][0])[:8] + '_' + str(int(data_temp2['orbit'][0])) + "_" + data_temp2['target_id'][0].astype(str) + '.png'): print(out_dir_temp + '/' + data_temp2['production_string'][0].astype(str) + '/' + var_string + '/OCO3_' + data_temp2['production_string'][0].astype(str) + "_" + var_string + '_' + str(data_temp2['sounding_id'][0])[:8] + '_' + str(int(data_temp2['orbit'][0])) + "_" + data_temp2['target_id'][0].astype(str) + '.png already exists!') else: fig, ax1 = plt.subplots(figsize=[20, 20]) m1 = Basemap(llcrnrlon=W, llcrnrlat=S, urcrnrlon=E, urcrnrlat=N, epsg=3857, resolution='h') try: m1.arcgisimage(service='World_Imagery', xpixels=2000, verbose=True) except: #Sometimes this fails randomly, so try again time.sleep(20) m1.arcgisimage(service='World_Imagery', xpixels=2000, verbose=True) m1.drawmeridians(np.linspace(W, E, 6)[1:-1], labels=[0, 0, 0, 1], size=24, color='0.75') m1.drawparallels(np.linspace(N, S, 6)[1:-1], labels=[1, 0, 0, 0], size=24, color='0.75') m1.drawcoastlines() #Map Scale. Have to hack because the Basemap drawmapscale function is broken, but this should work. Cartopy doesn't even have a map scale function. lat0 = S + (N - S) * 0.04 + 0.02 #0.04 lon0 = W + (E - W) * 0.04 distance = 40. / np.cos(lat0 * np.pi / 180.) corner_buffered_m1 = m1(lon0, lat0) corner_buffered_lon, corner_buffered_lat = m1( corner_buffered_m1[0] + (distance / 2 * 1000), corner_buffered_m1[1], inverse=True) scale = m1.drawmapscale(corner_buffered_lon, corner_buffered_lat, corner_buffered_lon, corner_buffered_lat, distance, units='km', fontcolor='w', fontsize=16, yoffset=2000) scale[3].set_text(40) #Plot footprints x1, y1 = m1(data_temp2['vertex_longitude_1'], data_temp2['vertex_latitude_1']) x2, y2 = m1(data_temp2['vertex_longitude_2'], data_temp2['vertex_latitude_2']) x3, y3 = m1(data_temp2['vertex_longitude_3'], data_temp2['vertex_latitude_3']) x4, y4 = m1(data_temp2['vertex_longitude_4'], data_temp2['vertex_latitude_4']) patches = [] for i in range(len(x1)): if (x1[i] == 0.0) | (x2[i] == 0.0) | (x3[i] == 0.0) | (x4[i] == 0.0): print("Bad vertex...") else: patches += [ Polygon([(x1[i], y1[i]), (x2[i], y2[i]), (x3[i], y3[i]), (x4[i], y4[i])]) ] p = PatchCollection(patches, alpha=1.) p.set_array(data_temp2[var_temp]) if var_temp == 'dp': p.set_clim( -1 * max(np.abs(np.percentile(data_temp2[var_temp], 10)), np.abs(np.percentile(data_temp2[var_temp], 90))), max(np.abs(np.percentile(data_temp2[var_temp], 10)), np.abs(np.percentile(data_temp2[var_temp], 90)))) elif var_temp == 'aod_total': p.set_clim(0, max(0.3, np.percentile(data_temp2[var_temp], 90))) else: p.set_clim(np.percentile(data_temp2[var_temp], 10), np.percentile(data_temp2[var_temp], 90)) p.set_lw(1.0) p.set_cmap(var_cbar) ax1.add_collection(p) #Colorbar divider = make_axes_locatable(ax1) cax = divider.append_axes("right", size=0.4, pad=0.25) if var_temp == 'aod_total': cbar = fig.colorbar(p, extend='max', cax=cax) else: cbar = fig.colorbar(p, extend='both', cax=cax) cbar.set_label(var_cbar_string, size=28, rotation=270, labelpad=35) cbar.ax.tick_params(labelsize=22) cbar.ax.yaxis.get_offset_text().set_fontsize(22) #Title title = ax1.set_title( 'OCO-3 ' + var_title_string + '\n' + data_temp2['sounding_operation_mode_string'][0].astype(str) + ' Mode (' + data_temp2['sounding_pcs_data_source_string'][0].astype(str) + '), ' + data_temp2['target_id'][0].astype(str) + ', "' + data_temp2['target_name'][0].astype(str) + '"\n' + data_temp2['production_string'][0].astype(str) + '\n' + hour_str + ':' + minute_str + ' UTC ' + day_str + ' ' + month_str + ' ' + year_str + ', Orbit ' + str(int(data_temp2['orbit'][0])), size=30, y=1.01) #Time stamp plt.text(0.99, 0.01, "Created " + str(datetime.datetime.now().day) + ' ' + calendar.month_abbr[datetime.datetime.now().month] + ' ' + str(datetime.datetime.now().year) + "\nCourtesy NASA/JPL-Caltech (R. R. Nelson)", ha='right', va='bottom', transform=ax1.transAxes, color='1.0', size=18) #Preliminary data stamp plt.text(0.01, 0.99, "PRELIMINARY (vEarly)", ha='left', va='top', transform=ax1.transAxes, color='r', size=18) #Globe inset ax2 = inset_axes(ax1, width=2., height=2.) m2 = Basemap(projection='ortho', lat_0=((N + S) / 2.), lon_0=((E + W) / 2.), resolution='l') m2.bluemarble() x1_globe, y1_globe = m2(((W + E) / 2.), ((N + S) / 2.)) m2.scatter(x1_globe, y1_globe, c='r', s=100, marker='*') #Mark the target x1_target, y1_target = m1(data_temp2['target_lon'][0], data_temp2['target_lat'][0]) ax1.scatter(x1_target, y1_target, c='r', marker="*", s=600) #Create save directory if it doesn't exist if not os.path.exists( out_dir_temp + '/' + data_temp2['production_string'][0].astype(str) + '/' + var_string): os.makedirs(out_dir_temp + '/' + data_temp2['production_string'][0].astype(str) + '/' + var_string) #Save figure print("Saving as " + out_dir_temp + '/' + data_temp2['production_string'][0].astype(str) + '/' + var_string + '/OCO3_' + data_temp2['production_string'][0].astype(str) + "_" + var_string + '_' + str(data_temp2['sounding_id'][0])[:8] + '_' + str(int(data_temp2['orbit'][0])) + "_" + data_temp2['target_id'][0].astype(str) + '.png')
def plot(self,**kargs): bathy = kargs.get('bathy','contourf') hvals = kargs.get('hvals','auto') resolution = kargs.get('res','i') rivers = kargs.get('rivers',False) parallels = kargs.get('parallels','auto') meridians = kargs.get('meridians','auto') scale = kargs.get('scale',False) states = kargs.get('states',False) xlim = kargs.get('xlim',False) ylim = kargs.get('ylim',False) title = kargs.get('title','auto') cmap = kargs.get('cmap',pylab.cm.gist_earth_r) proj = kargs.get('proj','merc') ax = kargs.get('ax',False) if not ax: fig=pylab.figure() ax=pylab.axes() else: fig=ax.figure h=np.ma.masked_where(self.mask==0,self.h) xb,yb=self.border() xt=ticks.loose_label(self.lon.min(),self.lon.max()) yt=ticks.loose_label(self.lat.min(),self.lat.max()) ht=ticks.loose_label_n(self.h.min(),self.h.max(),7) if xlim: Lonlims=xlim else: Lonlims=xt[0],xt[-1] if ylim: Latlims=ylim else: Latlims=yt[0],yt[-1] if hvals=='auto': hvals=ht if parallels=='auto': parallels=yt if meridians=='auto': meridians=xt if Basemap and proj: m = Basemap(projection=proj,lat_ts=0.0, #lon_0=self.lon[0].mean(), resolution=resolution, urcrnrlon=Lonlims[1], urcrnrlat=Latlims[1], llcrnrlon=Lonlims[0], llcrnrlat=Latlims[0]) m.drawcoastlines(ax=ax) m.fillcontinents(ax=ax,color=(0.7604, 1.0000, 0.7459)) if rivers: m.drawrivers(color='b') m.drawcountries(ax=ax) # m.drawlsmask() # m.drawmapboundary() if scale: dx=Lonlims[1]-Lonlims[0] dy=Latlims[1]-Latlims[0] lon=Lonlims[1]-dx/10 lat=Latlims[0]+dy/10 lon0=lon lat0=lat length=100 m.drawmapscale(lon,lat,lon0,lat0,length,ax=ax) if states: m.drawstates(ax=ax) m.drawparallels(parallels, labels=[1,0,0,0],ax=ax) m.drawmeridians(meridians, labels=[0,0,0,1],ax=ax) x, y = m(self.lon, self.lat) pch=False if bathy in ['pcolor','pcolormesh']: pch = ax.pcolormesh(x,y,h,cmap=cmap) elif bathy=='contour': pch = ax.contour(x,y,h,hvals,cmap=cmap) elif bathy=='contourf': pch = ax.contourf(x,y,h,hvals,cmap=cmap) if pch: if m.xmax-m.xmin<m.ymax-m.ymin: orientation='horizontal' else: orientation='vetical' cbh = pylab.colorbar(pch,orientation=orientation,ax=ax) cbh.set_label('Depth') if title=='auto': ax.set_title(self.name) elif title: ax.set_title(title) xb, yb = m(xb,yb) ax.plot(xb,yb) ax.axis([m.xmin, m.xmax, m.ymin, m.ymax]) return m else: ax.pcolormesh(self.lon,self.lat,h,cmap=cmap) ax.contour(self.lon,self.lat,self.h,hvals,colors='w') ax.plot(xb,yb)
barlength = 40 x_offset_scale = 0.17 y_offset_scale = 0.15 label_x_offs = 2 label_y_offs = 2.5 ax.axis([25, 230, 15, 165]) else: barlength = 5000 x_offset_scale = 0.2 y_offset_scale = 0.05 label_x_offs = 150 label_y_offs = 200 basemap.drawmapscale(lon=bbox[0] - x_offset_scale * (bbox[0] - bbox[2]), lat=bbox[1] - y_offset_scale * (bbox[1] - bbox[3]), lon0=bbox[0] - x_offset_scale * (bbox[0] - bbox[2]), lat0=bbox[1] - y_offset_scale * (bbox[1] - bbox[3]), length=barlength, units='m', barstyle='fancy', fontsize=18) ''' if options.input_type == "manual": for i, receiver_pos in enumerate(receivers_positions): receivers_positions[i] = basemap(receiver_pos[0],receiver_pos[1]) ''' reference_selection = options.reference_selection receivers_ignored = eval(options.ignore_sensors) for idx in range(len(receivers_ignored)): receivers_ignored[idx] -= 1 #TODO: axis ticks -> bad documentation #ax.set_xticks(np.linspace(x0,x1,int(x/10)))
def modelMap(grids, shakefile=None, suptitle=None, inventory_shapefile=None, plotorder=None, maskthreshes=None, colormaps=None, boundaries=None, zthresh=0, scaletype='continuous', lims=None, logscale=False, ALPHA=0.7, maproads=True, mapcities=True, isScenario=False, roadfolder=None, topofile=None, cityfile=None, oceanfile=None, roadcolor='#6E6E6E', watercolor='#B8EEFF', countrycolor='#177F10', outputdir=None, savepdf=True, savepng=True, showplots=False, roadref='unknown', cityref='unknown', oceanref='unknown', printparam=False, ds=True, dstype='mean', upsample=False): """ This function creates maps of mapio grid layers (e.g. liquefaction or landslide models with their input layers) All grids must use the same bounds TO DO change so that all input layers do not have to have the same bounds, test plotting multiple probability layers, and add option so that if PDF and PNG aren't output, opens plot on screen using plt.show() :param grids: Dictionary of N layers and metadata formatted like: maplayers['layer name']={ 'grid': mapio grid2D object, 'label': 'label for colorbar and top line of subtitle', 'type': 'output or input to model', 'description': 'detailed description of layer for subtitle'}. Layer names must be unique. :type name: Dictionary or Ordered dictionary - import collections; grids = collections.OrderedDict() :param shakefile: optional ShakeMap file (url or full file path) to extract information for labels and folder names :type shakefile: Shakemap Event Dictionary :param suptitle: This will be displayed at the top of the plots and in the figure names :type suptitle: string :param plotorder: List of keys describing the order to plot the grids, if None and grids is an ordered dictionary, it will use the order of the dictionary, otherwise it will choose order which may be somewhat random but it will always put a probability grid first :type plotorder: list :param maskthreshes: N x 1 array or list of lower thresholds for masking corresponding to order in plotorder or order of OrderedDict if plotorder is None. If grids is not an ordered dict and plotorder is not specified, this will not work right. If None (default), nothing will be masked :param colormaps: List of strings of matplotlib colormaps (e.g. cm.autumn_r) corresponding to plotorder or order of dictionary if plotorder is None. The list can contain both strings and None e.g. colormaps = ['cm.autumn', None, None, 'cm.jet'] and None's will default to default colormap :param boundaries: None to show entire study area, 'zoom' to zoom in on the area of action (only works if there is a probability layer) using zthresh as a threshold, or a dictionary defining lats and lons in the form of boundaries.xmin = minlon, boundaries.xmax = maxlon, boundaries.ymin = min lat, boundaries.ymax = max lat :param zthresh: threshold for computing zooming bounds, only used if boundaries = 'zoom' :type zthresh: float :param scaletype: Type of scale for plotting, 'continuous' or 'binned' - will be reflected in colorbar :type scaletype: string :param lims: None or Nx1 list of tuples or numpy arrays corresponding to plotorder defining the limits for saturating the colorbar (vmin, vmax) if scaletype is continuous or the bins to use (clev) if scaletype if binned. The list can contain tuples, arrays, and Nones, e.g. lims = [(0., 10.), None, (0.1, 1.5), np.linspace(0., 1.5, 15)]. When None is specified, the program will estimate the limits, when an array is specified but the scale type is continuous, vmin will be set to min(array) and vmax will be set to max(array) :param lims: None or Nx1 list of Trues and Falses corresponding to plotorder defining whether to use a linear or log scale (log10) for plotting the layer. This will be reflected in the labels :param ALPHA: Transparency for mapping, if there is a hillshade that will plot below each layer, it is recommended to set this to at least 0.7 :type ALPHA: float :param maproads: Whether to show roads or not, default True, but requires that roadfile is specified and valid to work :type maproads: boolean :param mapcities: Whether to show cities or not, default True, but requires that cityfile is specified and valid to work :type mapcities: boolean :param isScenario: Whether this is a scenario (True) or a real event (False) (default False) :type isScenario: boolean :param roadfolder: Full file path to folder containing road shapefiles :type roadfolder: string :param topofile: Full file path to topography grid (GDAL compatible) - this is only needed to make a hillshade if a premade hillshade is not specified :type topofile: string :param cityfile: Full file path to Pager file containing city & population information :type cityfile: string :param roadcolor: Color to use for roads, if plotted, default #6E6E6E :type roadcolor: Hex color or other matplotlib compatible way of defining color :param watercolor: Color to use for oceans, lakes, and rivers, default #B8EEFF :type watercolor: Hex color or other matplotlib compatible way of defining color :param countrycolor: Color for country borders, default #177F10 :type countrycolor: Hex color or other matplotlib compatible way of defining color :param outputdir: File path for outputting figures, if edict is defined, a subfolder based on the event id will be created in this folder. If None, will use current directory :param savepdf: True to save pdf figure, False to not :param savepng: True to save png figure, False to not :param ds: True to allow downsampling for display (necessary when arrays are quite large, False to not allow) :param dstype: What function to use in downsampling, options are 'min', 'max', 'median', or 'mean' :param upsample: True to upsample the layer to the DEM resolution for better looking hillshades :returns: * PDF and/or PNG of map * Downsampled and trimmed version of input grids. If no modification was needed for plotting, this will be identical to grids but without the metadata """ if suptitle is None: suptitle = ' ' plt.ioff() defaultcolormap = cm.jet if shakefile is not None: edict = ShakeGrid.load(shakefile, adjust='res').getEventDict() temp = ShakeGrid.load(shakefile, adjust='res').getShakeDict() edict['eventid'] = temp['shakemap_id'] edict['version'] = temp['shakemap_version'] else: edict = None # Get output file location if outputdir is None: print('No output location given, using current directory for outputs\n') outputdir = os.getcwd() if edict is not None: outfolder = os.path.join(outputdir, edict['event_id']) else: outfolder = outputdir if not os.path.isdir(outfolder): os.makedirs(outfolder) # Get plotting order, if not specified if plotorder is None: plotorder = list(grids.keys()) # Get boundaries to use for all plots cut = True if boundaries is None: cut = False keytemp = list(grids.keys()) boundaries = grids[keytemp[0]]['grid'].getGeoDict() elif boundaries == 'zoom': # Find probability layer (will just take the maximum bounds if there is # more than one) keytemp = list(grids.keys()) key1 = [key for key in keytemp if 'model' in key.lower()] if len(key1) == 0: print('Could not find model layer to use for zoom, using default boundaries') keytemp = list(grids.keys()) boundaries = grids[keytemp[0]]['grid'].getGeoDict() else: lonmax = -1.e10 lonmin = 1.e10 latmax = -1.e10 latmin = 1.e10 for key in key1: # get lat lons of areas affected and add, if no areas affected, # switch to shakemap boundaries temp = grids[key]['grid'] xmin, xmax, ymin, ymax = temp.getBounds() lons = np.linspace(xmin, xmax, temp.getGeoDict().nx) lats = np.linspace(ymax, ymin, temp.getGeoDict().ny) # backwards so it plots right row, col = np.where(temp.getData() > float(zthresh)) lonmin = lons[col].min() lonmax = lons[col].max() latmin = lats[row].min() latmax = lats[row].max() # llons, llats = np.meshgrid(lons, lats) # make meshgrid # llons1 = llons[temp.getData() > float(zthresh)] # llats1 = llats[temp.getData() > float(zthresh)] # if llons1.min() < lonmin: # lonmin = llons1.min() # if llons1.max() > lonmax: # lonmax = llons1.max() # if llats1.min() < latmin: # latmin = llats1.min() # if llats1.max() > latmax: # latmax = llats1.max() boundaries1 = {'dx': 100, 'dy': 100., 'nx': 100., 'ny': 100} # dummy fillers, only really care about bounds if xmin < lonmin-0.15*(lonmax-lonmin): boundaries1['xmin'] = lonmin-0.1*(lonmax-lonmin) else: boundaries1['xmin'] = xmin if xmax > lonmax+0.15*(lonmax-lonmin): boundaries1['xmax'] = lonmax+0.1*(lonmax-lonmin) else: boundaries1['xmax'] = xmax if ymin < latmin-0.15*(latmax-latmin): boundaries1['ymin'] = latmin-0.1*(latmax-latmin) else: boundaries1['ymin'] = ymin if ymax > latmax+0.15*(latmax-latmin): boundaries1['ymax'] = latmax+0.1*(latmax-latmin) else: boundaries1['ymax'] = ymax boundaries = GeoDict(boundaries1, adjust='res') else: # SEE IF BOUNDARIES ARE SAME AS BOUNDARIES OF LAYERS keytemp = list(grids.keys()) tempgdict = grids[keytemp[0]]['grid'].getGeoDict() if np.abs(tempgdict.xmin-boundaries['xmin']) < 0.05 and \ np.abs(tempgdict.ymin-boundaries['ymin']) < 0.05 and \ np.abs(tempgdict.xmax-boundaries['xmax']) < 0.05 and \ np.abs(tempgdict.ymax - boundaries['ymax']) < 0.05: print('Input boundaries are almost the same as specified boundaries, no cutting needed') boundaries = tempgdict cut = False else: try: if boundaries['xmin'] > boundaries['xmax'] or \ boundaries['ymin'] > boundaries['ymax']: print('Input boundaries are not usable, using default boundaries') keytemp = list(grids.keys()) boundaries = grids[keytemp[0]]['grid'].getGeoDict() cut = False else: # Build dummy GeoDict boundaries = GeoDict({'xmin': boundaries['xmin'], 'xmax': boundaries['xmax'], 'ymin': boundaries['ymin'], 'ymax': boundaries['ymax'], 'dx': 100., 'dy': 100., 'ny': 100., 'nx': 100.}, adjust='res') except: print('Input boundaries are not usable, using default boundaries') keytemp = list(grids.keys()) boundaries = grids[keytemp[0]]['grid'].getGeoDict() cut = False # Pull out bounds for various uses bxmin, bxmax, bymin, bymax = boundaries.xmin, boundaries.xmax, boundaries.ymin, boundaries.ymax # Determine if need a single panel or multi-panel plot and if multi-panel, # how many and how it will be arranged fig = plt.figure() numpanels = len(grids) if numpanels == 1: rowpan = 1 colpan = 1 # create the figure and axes instances. fig.set_figwidth(5) elif numpanels == 2 or numpanels == 4: rowpan = np.ceil(numpanels/2.) colpan = 2 fig.set_figwidth(13) else: rowpan = np.ceil(numpanels/3.) colpan = 3 fig.set_figwidth(15) if rowpan == 1: fig.set_figheight(rowpan*6.0) else: fig.set_figheight(rowpan*5.3) # Need to update naming to reflect the shakemap version once can get # getHeaderData to work, add edict['version'] back into title, maybe # shakemap id also? fontsizemain = 14. fontsizesub = 12. fontsizesmallest = 10. if rowpan == 1.: fontsizemain = 12. fontsizesub = 10. fontsizesmallest = 8. if edict is not None: if isScenario: title = edict['event_description'] else: timestr = edict['event_timestamp'].strftime('%b %d %Y') title = 'M%.1f %s v%i - %s' % (edict['magnitude'], timestr, edict['version'], edict['event_description']) plt.suptitle(title+'\n'+suptitle, fontsize=fontsizemain) else: plt.suptitle(suptitle, fontsize=fontsizemain) clear_color = [0, 0, 0, 0.0] # Cut all of them and release extra memory xbuff = (bxmax-bxmin)/10. ybuff = (bymax-bymin)/10. cutxmin = bxmin-xbuff cutymin = bymin-ybuff cutxmax = bxmax+xbuff cutymax = bymax+ybuff if cut is True: newgrids = collections.OrderedDict() for k, layer in enumerate(plotorder): templayer = grids[layer]['grid'] try: newgrids[layer] = {'grid': templayer.cut(cutxmin, cutxmax, cutymin, cutymax, align=True)} except Exception as e: print(('Cutting failed, %s, continuing with full layers' % e)) newgrids = grids continue del templayer gc.collect() else: newgrids = grids tempgdict = newgrids[list(grids.keys())[0]]['grid'].getGeoDict() # Upsample layers to same as topofile if desired for better looking hillshades if upsample is True and topofile is not None: try: topodict = GDALGrid.getFileGeoDict(topofile) if topodict.dx >= tempgdict.dx or topodict.dy >= tempgdict.dy: print('Upsampling not possible, resolution of results already smaller than DEM') pass else: tempgdict1 = GeoDict({'xmin': tempgdict.xmin-xbuff, 'ymin': tempgdict.ymin-ybuff, 'xmax': tempgdict.xmax+xbuff, 'ymax': tempgdict.ymax+ybuff, 'dx': topodict.dx, 'dy': topodict.dy, 'nx': topodict.nx, 'ny': topodict.ny}, adjust='res') tempgdict2 = tempgdict1.getBoundsWithin(tempgdict) for k, layer in enumerate(plotorder): newgrids[layer]['grid'] = newgrids[layer]['grid'].subdivide(tempgdict2) except: print('Upsampling failed, continuing') # Downsample all of them for plotting, if needed, and replace them in # grids (to save memory) tempgrid = newgrids[list(grids.keys())[0]]['grid'] xsize = tempgrid.getGeoDict().nx ysize = tempgrid.getGeoDict().ny inchesx, inchesy = fig.get_size_inches() divx = int(np.round(xsize/(500.*inchesx))) divy = int(np.round(ysize/(500.*inchesy))) xmin, xmax, ymin, ymax = tempgrid.getBounds() gdict = tempgrid.getGeoDict() # Will be replaced if downsampled del tempgrid gc.collect() if divx <= 1: divx = 1 if divy <= 1: divy = 1 if (divx > 1. or divy > 1.) and ds: if dstype == 'max': func = np.nanmax elif dstype == 'min': func = np.nanmin elif dstype == 'med': func = np.nanmedian else: func = np.nanmean for k, layer in enumerate(plotorder): layergrid = newgrids[layer]['grid'] dat = block_reduce(layergrid.getData().copy(), block_size=(divy, divx), cval=float('nan'), func=func) if k == 0: lons = block_reduce(np.linspace(xmin, xmax, layergrid.getGeoDict().nx), block_size=(divx,), func=np.mean, cval=float('nan')) if math.isnan(lons[-1]): lons[-1] = lons[-2] + (lons[1]-lons[0]) lats = block_reduce(np.linspace(ymax, ymin, layergrid.getGeoDict().ny), block_size=(divy,), func=np.mean, cval=float('nan')) if math.isnan(lats[-1]): lats[-1] = lats[-2] + (lats[1]-lats[0]) gdict = GeoDict({'xmin': lons.min(), 'xmax': lons.max(), 'ymin': lats.min(), 'ymax': lats.max(), 'dx': np.abs(lons[1]-lons[0]), 'dy': np.abs(lats[1]-lats[0]), 'nx': len(lons), 'ny': len(lats)}, adjust='res') newgrids[layer]['grid'] = Grid2D(dat, gdict) del layergrid, dat else: lons = np.linspace(xmin, xmax, xsize) lats = np.linspace(ymax, ymin, ysize) # backwards so it plots right side up #make meshgrid llons1, llats1 = np.meshgrid(lons, lats) # See if there is an oceanfile for masking bbox = PolygonSH(((cutxmin, cutymin), (cutxmin, cutymax), (cutxmax, cutymax), (cutxmax, cutymin))) if oceanfile is not None: try: f = fiona.open(oceanfile) oc = next(f) f.close shapes = shape(oc['geometry']) # make boundaries into a shape ocean = shapes.intersection(bbox) except: print('Not able to read specified ocean file, will use default ocean masking') oceanfile = None if inventory_shapefile is not None: try: f = fiona.open(inventory_shapefile) invshp = list(f.items(bbox=(bxmin, bymin, bxmax, bymax))) f.close() inventory = [shape(inv[1]['geometry']) for inv in invshp] except: print('unable to read inventory shapefile specified, will not plot inventory') inventory_shapefile = None # # Find cities that will be plotted if mapcities is True and cityfile is not None: try: mycity = BasemapCities.loadFromGeoNames(cityfile=cityfile) bcities = mycity.limitByBounds((bxmin, bxmax, bymin, bymax)) #bcities = bcities.limitByPopulation(40000) bcities = bcities.limitByGrid(nx=4, ny=4, cities_per_grid=2) except: print('Could not read in cityfile, not plotting cities') mapcities = False cityfile = None # Load in topofile if topofile is not None: try: topomap = GDALGrid.load(topofile, resample=True, method='linear', samplegeodict=gdict) except: topomap = GMTGrid.load(topofile, resample=True, method='linear', samplegeodict=gdict) topodata = topomap.getData().copy() # mask oceans if don't have ocean shapefile if oceanfile is None: topodata = maskoceans(llons1, llats1, topodata, resolution='h', grid=1.25, inlands=True) else: print('no hillshade is possible\n') topomap = None topodata = None # Load in roads, if needed if maproads is True and roadfolder is not None: try: roadslist = [] for folder in os.listdir(roadfolder): road1 = os.path.join(roadfolder, folder) shpfiles = glob.glob(os.path.join(road1, '*.shp')) if len(shpfiles): shpfile = shpfiles[0] f = fiona.open(shpfile) shapes = list(f.items(bbox=(bxmin, bymin, bxmax, bymax))) for shapeid, shapedict in shapes: roadslist.append(shapedict) f.close() except: print('Not able to plot roads') roadslist = None val = 1 for k, layer in enumerate(plotorder): layergrid = newgrids[layer]['grid'] if 'label' in list(grids[layer].keys()): label1 = grids[layer]['label'] else: label1 = layer try: sref = grids[layer]['description']['name'] except: sref = None ax = fig.add_subplot(rowpan, colpan, val) val += 1 clat = bymin + (bymax-bymin)/2.0 clon = bxmin + (bxmax-bxmin)/2.0 # setup of basemap ('lcc' = lambert conformal conic). # use major and minor sphere radii from WGS84 ellipsoid. m = Basemap(llcrnrlon=bxmin, llcrnrlat=bymin, urcrnrlon=bxmax, urcrnrlat=bymax, rsphere=(6378137.00, 6356752.3142), resolution='l', area_thresh=1000., projection='lcc', lat_1=clat, lon_0=clon, ax=ax) x1, y1 = m(llons1, llats1) # get projection coordinates axsize = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted()) if k == 0: wid, ht = axsize.width, axsize.height if colormaps is not None and \ len(colormaps) == len(newgrids) and \ colormaps[k] is not None: palette = colormaps[k] else: # Find preferred default color map for each type of layer if 'prob' in layer.lower() or 'pga' in layer.lower() or \ 'pgv' in layer.lower() or 'cohesion' in layer.lower() or \ 'friction' in layer.lower() or 'fs' in layer.lower(): palette = cm.jet elif 'slope' in layer.lower(): palette = cm.gnuplot2 elif 'precip' in layer.lower(): palette = cm2.s3pcpn else: palette = defaultcolormap if topodata is not None: if k == 0: ptopo = m.transform_scalar( np.flipud(topodata), lons+0.5*gdict.dx, lats[::-1]-0.5*gdict.dy, np.round(300.*wid), np.round(300.*ht), returnxy=False, checkbounds=False, order=1, masked=False) #use lightsource class to make our shaded topography ls = LightSource(azdeg=135, altdeg=45) ls1 = LightSource(azdeg=120, altdeg=45) ls2 = LightSource(azdeg=225, altdeg=45) intensity1 = ls1.hillshade(ptopo, fraction=0.25, vert_exag=1.) intensity2 = ls2.hillshade(ptopo, fraction=0.25, vert_exag=1.) intensity = intensity1*0.5 + intensity2*0.5 #hillshm_im = m.transform_scalar(np.flipud(hillshm), lons, lats[::-1], np.round(300.*wid), np.round(300.*ht), returnxy=False, checkbounds=False, order=0, masked=False) #m.imshow(hillshm_im, cmap='Greys', vmin=0., vmax=3., zorder=1, interpolation='none') # vmax = 3 to soften colors to light gray #m.pcolormesh(x1, y1, hillshm, cmap='Greys', linewidth=0., rasterized=True, vmin=0., vmax=3., edgecolors='none', zorder=1); # plt.draw() # Get the data dat = layergrid.getData().copy() # mask out anything below any specified thresholds # Might need to move this up to before downsampling...might give illusion of no hazard in places where there is some that just got averaged out if maskthreshes is not None and len(maskthreshes) == len(newgrids): if maskthreshes[k] is not None: dat[dat <= maskthreshes[k]] = float('NaN') dat = np.ma.array(dat, mask=np.isnan(dat)) if logscale is not False and len(logscale) == len(newgrids): if logscale[k] is True: dat = np.log10(dat) label1 = r'$log_{10}$(' + label1 + ')' if scaletype.lower() == 'binned': # Find order of range to know how to scale order = np.round(np.log(np.nanmax(dat) - np.nanmin(dat))) if order < 1.: scal = 10**-order else: scal = 1. if lims is None or len(lims) != len(newgrids): clev = (np.linspace(np.floor(scal*np.nanmin(dat)), np.ceil(scal*np.nanmax(dat)), 10))/scal else: if lims[k] is None: clev = (np.linspace(np.floor(scal*np.nanmin(dat)), np.ceil(scal*np.nanmax(dat)), 10))/scal else: clev = lims[k] # Adjust to colorbar levels dat[dat < clev[0]] = clev[0] for j, level in enumerate(clev[:-1]): dat[(dat >= clev[j]) & (dat < clev[j+1])] = clev[j] # So colorbar saturates at top dat[dat > clev[-1]] = clev[-1] #panelhandle = m.contourf(x1, y1, datm, clev, cmap=palette, linewidth=0., alpha=ALPHA, rasterized=True) vmin = clev[0] vmax = clev[-1] else: if lims is not None and len(lims) == len(newgrids): if lims[k] is None: vmin = np.nanmin(dat) vmax = np.nanmax(dat) else: vmin = lims[k][0] vmax = lims[k][-1] else: vmin = np.nanmin(dat) vmax = np.nanmax(dat) # Mask out cells overlying oceans or block with a shapefile if available if oceanfile is None: dat = maskoceans(llons1, llats1, dat, resolution='h', grid=1.25, inlands=True) else: #patches = [] if type(ocean) is PolygonSH: ocean = [ocean] for oc in ocean: patch = getProjectedPatch(oc, m, edgecolor="#006280", facecolor=watercolor, lw=0.5, zorder=4.) #x, y = m(oc.exterior.xy[0], oc.exterior.xy[1]) #xy = zip(x, y) #patch = Polygon(xy, facecolor=watercolor, edgecolor="#006280", lw=0.5, zorder=4.) ##patches.append(Polygon(xy, facecolor=watercolor, edgecolor=watercolor, zorder=500.)) ax.add_patch(patch) ##ax.add_collection(PatchCollection(patches)) if inventory_shapefile is not None: for in1 in inventory: if 'point' in str(type(in1)): x, y = in1.xy x = x[0] y = y[0] m.scatter(x, y, c='m', s=50, latlon=True, marker='^', zorder=100001) else: x, y = m(in1.exterior.xy[0], in1.exterior.xy[1]) xy = list(zip(x, y)) patch = Polygon(xy, facecolor='none', edgecolor='k', lw=0.5, zorder=10.) #patches.append(Polygon(xy, facecolor=watercolor, edgecolor=watercolor, zorder=500.)) ax.add_patch(patch) palette.set_bad(clear_color, alpha=0.0) # Plot it up dat_im = m.transform_scalar( np.flipud(dat), lons+0.5*gdict.dx, lats[::-1]-0.5*gdict.dy, np.round(300.*wid), np.round(300.*ht), returnxy=False, checkbounds=False, order=0, masked=True) if topodata is not None: # Drape over hillshade #turn data into an RGBA image cmap = palette #adjust data so scaled between vmin and vmax and between 0 and 1 dat1 = dat_im.copy() dat1[dat1 < vmin] = vmin dat1[dat1 > vmax] = vmax dat1 = (dat1 - vmin)/(vmax-vmin) rgba_img = cmap(dat1) maskvals = np.dstack((dat1.mask, dat1.mask, dat1.mask)) rgb = np.squeeze(rgba_img[:, :, 0:3]) rgb[maskvals] = 1. draped_hsv = ls.blend_hsv(rgb, np.expand_dims(intensity, 2)) m.imshow(draped_hsv, zorder=3., interpolation='none') # This is just a dummy layer that will be deleted to make the # colorbar look right panelhandle = m.imshow(dat_im, cmap=palette, zorder=0., vmin=vmin, vmax=vmax) else: panelhandle = m.imshow(dat_im, cmap=palette, zorder=3., vmin=vmin, vmax=vmax, interpolation='none') #panelhandle = m.pcolormesh(x1, y1, dat, linewidth=0., cmap=palette, vmin=vmin, vmax=vmax, alpha=ALPHA, rasterized=True, zorder=2.); #panelhandle.set_edgecolors('face') # add colorbar cbfmt = '%1.1f' if vmax is not None and vmin is not None: if (vmax - vmin) < 1.: cbfmt = '%1.2f' elif vmax > 5.: # (vmax - vmin) > len(clev): cbfmt = '%1.0f' #norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax) if scaletype.lower() == 'binned': cbar = fig.colorbar(panelhandle, spacing='proportional', ticks=clev, boundaries=clev, fraction=0.036, pad=0.04, format=cbfmt, extend='both') #cbar1 = ColorbarBase(cbar.ax, cmap=palette, norm=norm, spacing='proportional', ticks=clev, boundaries=clev, fraction=0.036, pad=0.04, format=cbfmt, extend='both', extendfrac='auto') else: cbar = fig.colorbar(panelhandle, fraction=0.036, pad=0.04, extend='both', format=cbfmt) #cbar1 = ColorbarBase(cbar.ax, cmap=palette, norm=norm, fraction=0.036, pad=0.04, extend='both', extendfrac='auto', format=cbfmt) if topodata is not None: panelhandle.remove() cbar.set_label(label1, fontsize=10) cbar.ax.tick_params(labelsize=8) parallels = m.drawparallels(getMapLines(bymin, bymax, 3), labels=[1, 0, 0, 0], linewidth=0.5, labelstyle='+/-', fontsize=9, xoffset=-0.8, color='gray', zorder=100.) m.drawmeridians(getMapLines(bxmin, bxmax, 3), labels=[0, 0, 0, 1], linewidth=0.5, labelstyle='+/-', fontsize=9, color='gray', zorder=100.) for par in parallels: try: parallels[par][1][0].set_rotation(90) except: pass #draw roads on the map, if they were provided to us if maproads is True and roadslist is not None: try: for road in roadslist: try: xy = list(road['geometry']['coordinates']) roadx, roady = list(zip(*xy)) mapx, mapy = m(roadx, roady) m.plot(mapx, mapy, roadcolor, lw=0.5, zorder=9) except: continue except Exception as e: print(('Failed to plot roads, %s' % e)) #add city names to map if mapcities is True and cityfile is not None: try: fontname = 'Arial' fontsize = 8 if k == 0: # Only need to choose cities first time and then apply to rest fcities = bcities.limitByMapCollision( m, fontname=fontname, fontsize=fontsize) ctlats, ctlons, names = fcities.getCities() cxis, cyis = m(ctlons, ctlats) for ctlat, ctlon, cxi, cyi, name in zip(ctlats, ctlons, cxis, cyis, names): m.scatter(ctlon, ctlat, c='k', latlon=True, marker='.', zorder=100000) ax.text(cxi, cyi, name, fontname=fontname, fontsize=fontsize, zorder=100000) except Exception as e: print('Failed to plot cities, %s' % e) #draw star at epicenter plt.sca(ax) if edict is not None: elat, elon = edict['lat'], edict['lon'] ex, ey = m(elon, elat) plt.plot(ex, ey, '*', markeredgecolor='k', mfc='None', mew=1.0, ms=15, zorder=10000.) m.drawmapboundary(fill_color=watercolor) m.fillcontinents(color=clear_color, lake_color=watercolor) m.drawrivers(color=watercolor) ##m.drawcoastlines() #draw country boundaries m.drawcountries(color=countrycolor, linewidth=1.0) #add map scale m.drawmapscale((bxmax+bxmin)/2., (bymin+(bymax-bymin)/9.), clon, clat, np.round((((bxmax-bxmin)*111)/5)/10.)*10, barstyle='fancy', zorder=10) # Add border autoAxis = ax.axis() rec = Rectangle((autoAxis[0]-0.7, autoAxis[2]-0.2), (autoAxis[1]-autoAxis[0])+1, (autoAxis[3]-autoAxis[2])+0.4, fill=False, lw=1, zorder=1e8) rec = ax.add_patch(rec) rec.set_clip_on(False) plt.draw() if sref is not None: label2 = '%s\nsource: %s' % (label1, sref) # '%s\n' % label1 + r'{\fontsize{10pt}{3em}\selectfont{}%s}' % sref # else: label2 = label1 plt.title(label2, axes=ax, fontsize=fontsizesub) #draw scenario watermark, if scenario if isScenario: plt.sca(ax) cx, cy = m(clon, clat) plt.text(cx, cy, 'SCENARIO', rotation=45, alpha=0.10, size=72, ha='center', va='center', color='red') #if ds: # Could add this to print "downsampled" on map # plt.text() if k == 1 and rowpan == 1: # adjust single level plot axsize = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted()) ht2 = axsize.height fig.set_figheight(ht2*1.6) else: plt.tight_layout() # Make room for suptitle - tight layout doesn't account for it plt.subplots_adjust(top=0.92) if printparam is True: try: fig = plt.gcf() dictionary = grids['model']['description']['parameters'] paramstring = 'Model parameters: ' halfway = np.ceil(len(dictionary)/2.) for i, key in enumerate(dictionary): if i == halfway and colpan == 1: paramstring += '\n' paramstring += ('%s = %s; ' % (key, dictionary[key])) print(paramstring) fig.text(0.01, 0.015, paramstring, fontsize=fontsizesmallest) plt.draw() except: print('Could not display model parameters') if edict is not None: eventid = edict['eventid'] else: eventid = '' time1 = datetime.datetime.utcnow().strftime('%d%b%Y_%H%M') outfile = os.path.join(outfolder, '%s_%s_%s.pdf' % (eventid, suptitle, time1)) pngfile = os.path.join(outfolder, '%s_%s_%s.png' % (eventid, suptitle, time1)) if savepdf is True: print('Saving map output to %s' % outfile) plt.savefig(outfile, dpi=300) if savepng is True: print('Saving map output to %s' % pngfile) plt.savefig(pngfile) if showplots is True: plt.show() else: plt.close(fig) return newgrids
vmin=zi.min(), vmax=zi.max(), zorder=10, ) # add colour bar and title # add colour bar, title, and scale cbar = plt.colorbar(con, orientation="vertical", fraction=0.057, pad=0.05) cbar.set_label("Richter Scale - Mw") m.drawmapscale( 24.0, -9.0, 28.0, -13, 100, units="km", fontsize=10, yoffset=None, barstyle="fancy", labelstyle="simple", fillcolor1="w", fillcolor2="#000000", fontcolor="#000000", zorder=5, ) plt.title("Earthquake Contour Map") plt.savefig("contour.png", format="png", dpi=300, transparent=True) plt.show()
def plotIce(u, cmap, scale='lin', name='', units='', numLvls=12, tp=False, tpAlpha=0.5): """ INPUTS : u : solution to plot. cmap : colormap to use - see images directory for sample and name scale : scale to plot, either 'log' or 'lin' name : title of the plot, latex accepted units : units for the colorbar, latex approved numLvls : number of levels for field values tp : boolean determins plotting of triangle overlay tpAlpha : alpha level of triangles 0.0 (transparent) - 1.0 (opaque) OUTPUT : A sigle 250 dpi .png in the source directory. """ #============================================================================= # format stuff that needs to be formatted : dec = 1 field = '' dec = 1 # data gathering : mesh = u.function_space().mesh() coord = mesh.coordinates() fi = mesh.cells() vv = u.compute_vertex_values(mesh) vx = coord[:,0] vy = coord[:,1] #============================================================================= # map functions : fig = plt.figure(figsize=(13.5,7), dpi=80) ax = fig.add_axes() # map projection that the data is based on : m = Basemap(projection='stere', lat_ts=70.0, lat_0=90.0, lon_0=-45.0, resolution='l', llcrnrlat=55,llcrnrlon=-55,urcrnrlat=80,urcrnrlon=0.0) # adjustment of x, y coordinates for N. polar projection : x = vx + m.projparams['x_0'] y = vy + m.projparams['y_0'] v = vv # conversion to lon, lat coordinates : lon, lat = m(x, y, inverse = True) # new projection of our choosing : m = Basemap(ax=ax, width=62000.0, height=26000.0, resolution='h',projection='stere', lat_ts=67.03, lon_0=-48.675, lat_0=67.03) m.etopo() # conversion to projection coordinates from lon, lat : x, y = m(lon, lat) m.drawcoastlines(linewidth=0.25, color = 'black') # draw lat/lon grid lines every 5 degrees. # labels = [left,right,top,bottom] m.drawmeridians(np.arange(0, 360, 0.25), color = 'black', labels = [False, False, False, True]) m.drawparallels(np.arange(-90, 90, 0.25), color = 'black', labels = [True, False, False, False]) m.drawmapscale(-48.25, 66.94, -48.675, 67.675, 10, yoffset=(0.01*(m.ymax-m.ymin)), barstyle='fancy') #============================================================================= # plotting : # countour levels : if scale == 'log': vmax = ceil(max(v)) if field == 'melt_rate': v[where(v<=0.0)] = 0.00001 #v[where(v<=0.0)] = 0.0 + min(v[where(v>0.0)])/10 levels = logspace(log10(0.001), log10(vmax), numLvls) #levels = [0.0001, 0.0002, 0.001, 0.002, 0.01, 0.02, # 0.04, 0.08, 0.20, 0.40,0.80 ] elif field == 'sliding_ratio': v[where(v<=0.0)] = 0.001 levels = logspace(log10(0.1), log10(2), numLvls) else: vmin = floor(min(v)) v[where(v<=0.0)] = 1.0 levels = logspace(0.0, log10(vmax+1), numLvls) from matplotlib.ticker import LogFormatter formatter = LogFormatter(10, labelOnlyBase=False) norm = colors.LogNorm() elif scale == 'lin': vmin = floor(min(v)) vmax = ceil(max(v)) levels = linspace(vmin, vmax+1, numLvls) from matplotlib.ticker import ScalarFormatter formatter = ScalarFormatter() norm = None elif scale == 'bool': levels = [0, 1, 2] from matplotlib.ticker import ScalarFormatter formatter = ScalarFormatter() norm = None # plots with generated triangles : cs = tripcolor(x, y, fi, v, shading='gouraud', cmap=get_cmap(cmap), norm=norm) #cs = tricontourf(x, y, fi, v, #levels=levels, # cmap=get_cmap(cmap), norm=norm) # plot triangles : if tp == True: tp = triplot(x, y, fi, '-', lw=0.2, alpha=tpAlpha) # include colorbar : if field != 'melted' : if field == 'beta2' or field == 'U_observed' or field == 'U_surface'\ or field == 'U_bed' or field == 'sliding_ratio': levels[0] = 0.0 cbar = m.colorbar(cs, format=formatter, ticks=around(levels,decimals=dec), location='right', pad="5%") elif field == 'T_surf' or field == 'T_basal': cbar = m.colorbar(cs, format=formatter, ticks=around(levels,decimals=dec), location='right', pad="5%") elif field == 'melt_rate': cbar = m.colorbar(cs, format=formatter, ticks=levels, location='right', pad="5%") elif field == 'sliding_ratio': levels[0] = 0.0 cbar = m.colorbar(cs, format=formatter, ticks=levels, location='right', pad="5%") else : cbar = m.colorbar(cs, format=formatter, ticks=around(levels,decimals=dec), location='right', pad="5%") # colorbar label : txt = figtext(.95, .50, units) txt.set_fontsize(20.0) tit = title(name) savefig(name + '.png', dpi=250) show()
fig, axes = plt.subplots(2, 2) m1 = Basemap(projection='lcc', lat_0=lat.mean(), lon_0=lon.mean(), llcrnrlon=(-123), llcrnrlat=(58), urcrnrlon=(-108), urcrnrlat=(62), resolution='f', ax=axes[0][0]) m1.drawcoastlines(linewidth=0.3) m1.drawcountries() m1.drawparallels(np.arange(-50, 70, 5)) m1.drawmeridians(np.arange(-130, -100, 5)) m1.drawmapscale(-121, 58.7, lon.mean(), lat.mean(), 100) m1.drawparallels(np.arange(-50, 70, 5), linewidth=0.5, labels=[True, False, False, False]) m1.drawmeridians(np.arange(-130, -100, 5), linewidth=0.5, labels=[False, False, False, True]) map1 = m1.pcolormesh(lon, lat, Topo, latlon=True, cmap='terrain') axes[0][0].set_title('Height above mean sea level', fontsize=font_subtitle) cbar = fig.colorbar(map1, ax=axes[0][0], extend='max', shrink=0.8) cbar.set_label('m', fontsize=font_axes, rotation=0) cbar.ax.tick_params(labelsize=font_ticks) # Specify clear, discrete colorbar for LU (21 categories) # 1=Evergreen Needleleaf Forest, 2=Evergreen Broadleaf Forest, 3=Deciduous Needleleaf Forest # 4=Deciduous Broadleaf Forest, 5=Mixed Forest, 6=Closed Shrubland, 7=Open Shrubland. 8=Woody Savannah