from shapely import geometry demands = pd.read_csv('demands.csv', index_col=0) shortages = pd.read_csv('shortages.csv', index_col=0) structures = pd.read_csv('modeled_diversions.csv', index_col=0) for index, row in structures.iterrows(): structures.at[str(index), 'Mean demand'] = np.mean(demands.loc[str(index)].values) extent = [-109.069, -105.6, 38.85, 40.50] extent_large = [-111.0, -101.0, 36.5, 41.5] rivers_10m = cpf.NaturalEarthFeature('physical', 'rivers_lake_centerlines', '10m') tiles = cimgt.StamenTerrain(style='terrain') shape_feature = ShapelyFeature(Reader('Water_Districts.shp').geometries(), ccrs.PlateCarree(), edgecolor='black', facecolor='None') fig = plt.figure(figsize=(18, 9)) ax = plt.axes(projection=tiles.crs) ax.add_feature(rivers_10m, facecolor='None', edgecolor='royalblue', linewidth=2, zorder=4) ax.add_image(tiles, 9, interpolation='none', alpha=0.8) ax.set_extent(extent) ax.add_feature(shape_feature, facecolor='#a1a384', alpha=0.6) points = ax.scatter(structures['X'],
def add_inset(fig, extent, position, bounds=None, label=None, polygon=None, shades=True, hillshade=True, list_shp=None, main=False, markup=None, markpos='left', markadj=0, markup_sub=None, sub_pos='lt'): main_pos = [0.375, 0.21, 0.25, 0.25] if polygon is None and bounds is not None: polygon = poly_from_extent(bounds) if shades: shades_main_to_inset(main_pos, position, latlon_extent_to_robinson_axes_verts(polygon), label=label) sub_ax = fig.add_axes(position, projection=ccrs.Robinson(), label=label) sub_ax.set_extent(extent, ccrs.Geodetic()) sub_ax.add_feature( cfeature.NaturalEarthFeature('physical', 'ocean', '50m', facecolor='gainsboro')) sub_ax.add_feature( cfeature.NaturalEarthFeature('physical', 'land', '50m', facecolor='dimgrey')) if hillshade: def out_of_poly_mask(geoimg, poly_coords): poly = poly_from_coords(inter_poly_coords(poly_coords)) srs = osr.SpatialReference() srs.ImportFromEPSG(4326) # put in a memory vector ds_shp = create_mem_shp(poly, srs) return geoimg_mask_on_feat_shp_ds(ds_shp, geoimg) def inter_poly_coords(polygon_coords): list_lat_interp = [] list_lon_interp = [] for i in range(len(polygon_coords) - 1): lon_interp = np.linspace(polygon_coords[i][0], polygon_coords[i + 1][0], 50) lat_interp = np.linspace(polygon_coords[i][1], polygon_coords[i + 1][1], 50) list_lon_interp.append(lon_interp) list_lat_interp.append(lat_interp) all_lon_interp = np.concatenate(list_lon_interp) all_lat_interp = np.concatenate(list_lat_interp) return np.array(list(zip(all_lon_interp, all_lat_interp))) img = GeoImg(fn_hs) hs_tmp = hs_land.copy() hs_tmp_nl = hs_notland.copy() mask = out_of_poly_mask(img, polygon) hs_tmp[~mask] = 0 hs_tmp_nl[~mask] = 0 sub_ax.imshow(hs_tmp[:, :], extent=ext, transform=ccrs.Robinson(), cmap=cmap2, zorder=2, interpolation='nearest') sub_ax.imshow(hs_tmp_nl[:, :], extent=ext, transform=ccrs.Robinson(), cmap=cmap22, zorder=2, interpolation='nearest') if main: shape_feature = ShapelyFeature(Reader(list_shp).geometries(), ccrs.PlateCarree(), alpha=1, facecolor='indigo', linewidth=0.35, edgecolor='indigo') sub_ax.add_feature(shape_feature) if bounds is not None: verts = mpath.Path(latlon_extent_to_robinson_axes_verts(polygon)) sub_ax.set_boundary(verts, transform=sub_ax.transAxes) if not main: for i in range(len(tiles)): lat, lon = SRTMGL1_naming_to_latlon(tiles[i]) if group_by_spec: lat, lon = latlon_to_spec_center(lat, lon) else: lat = lat lon = lon if label == 'Arctic West' and ((lat < 71 and lon > 60) or (lat < 76 and lon > 100)): continue if label == 'HMA' and lat >= 46: continue # fac = 0.02 fac = 1500 if areas[i] > 10: rad = 15000 + np.sqrt(areas[i]) * fac else: rad = 15000 + 10 * fac # cmin = -1 # cmax = 1 col_bounds = np.array([ -1.5, -1.1, -0.8, -0.6, -0.4, -0.2, 0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6 ]) # col_bounds = np.array([-1, -0.7, -0.4, -0.2, -0.1, -0.05, 0.05, 0.1, 0.15, 0.2, 0.3, 0.5]) cb = [] cb_val = np.linspace(0, 1, len(col_bounds)) for j in range(len(cb_val)): cb.append(mpl.cm.RdYlBu(cb_val[j])) cmap_cus = mpl.colors.LinearSegmentedColormap.from_list( 'my_cb', list( zip((col_bounds - min(col_bounds)) / (max(col_bounds - min(col_bounds))), cb)), N=1000) if ~np.isnan(dhs[i]) and areas[i] > 0.2 and errs[ i] < 0.5: #and ((areas[i]>=5.) or label in ['Mexico','Indonesia','Africa']): dhdt = dhs[i] dhdt_col = max( 0.0001, min(0.9999, (dhdt - min(col_bounds)) / (max(col_bounds) - min(col_bounds)))) # ind = max(0, min(int((dhs[i]/20. - cmin) / (cmax - cmin) * 100), 99)) # if dhs[i]>=0: # ind = max(0, min(int((np.sqrt(dhs[i]/20.) - cmin) / (cmax - cmin) * 100), 99)) # else: # ind = max(0, min(int((-np.sqrt(-dhs[i]/20.) - cmin) / (cmax - cmin) * 100), 99)) col = cmap_cus(dhdt_col) # elif areas[i] <= 5: # continue elif areas[i] > 0.2: col = plt.cm.Greys(0.7) # col = 'black' # xy = [lon,lat] xy = coordXform(ccrs.PlateCarree(), ccrs.Robinson(), np.array([lon]), np.array([lat]))[0][0:2] sub_ax.add_patch( mpatches.Circle(xy=xy, radius=rad, facecolor=col, edgecolor='None', alpha=1, transform=ccrs.Robinson(), zorder=30)) # sub_ax.add_patch( # mpatches.Circle(xy=xy, radius=rad, facecolor='None', edgecolor='dimgrey', alpha=1, transform=ccrs.Robinson(), zorder=30)) if markup is not None: if markpos == 'left': lon_upleft = np.min(list(zip(*polygon))[0]) lat_upleft = np.max(list(zip(*polygon))[1]) else: lon_upleft = np.max(list(zip(*polygon))[0]) lat_upleft = np.max(list(zip(*polygon))[1]) robin = coordXform(ccrs.PlateCarree(), ccrs.Robinson(), np.array([lon_upleft]), np.array([lat_upleft])) rob_x = robin[0][0] rob_y = robin[0][1] size_y = 200000 size_x = 80000 * len(markup) + markadj if markpos == 'right': rob_x = rob_x - 50000 else: rob_x = rob_x + 50000 sub_ax_2 = fig.add_axes(position, projection=ccrs.Robinson(), label=label + 'markup') # sub_ax_2.add_patch(mpatches.Rectangle((rob_x, rob_y), size_x, size_y , linewidth=1, edgecolor='grey', facecolor='white',transform=ccrs.Robinson())) sub_ax_2.set_extent(extent, ccrs.Geodetic()) verts = mpath.Path(rect_units_to_verts([rob_x, rob_y, size_x, size_y])) sub_ax_2.set_boundary(verts, transform=sub_ax.transAxes) sub_ax_2.text(rob_x, rob_y + 50000, markup, horizontalalignment=markpos, verticalalignment='bottom', transform=ccrs.Robinson(), color='black', fontsize=4.5, fontweight='bold', bbox=dict(facecolor='white', alpha=1, linewidth=0.35, pad=1.5)) if markup_sub is not None: lon_min = np.min(list(zip(*polygon))[0]) lon_max = np.max(list(zip(*polygon))[0]) lon_mid = 0.5 * (lon_min + lon_max) lat_min = np.min(list(zip(*polygon))[1]) lat_max = np.max(list(zip(*polygon))[1]) lat_mid = 0.5 * (lat_min + lat_max) size_y = 150000 size_x = 150000 lat_midup = lat_min + 0.87 * (lat_max - lat_min) robin = coordXform( ccrs.PlateCarree(), ccrs.Robinson(), np.array([ lon_min, lon_min, lon_min, lon_mid, lon_mid, lon_max, lon_max, lon_max, lon_min ]), np.array([ lat_min, lat_mid, lat_max, lat_min, lat_max, lat_min, lat_mid, lat_max, lat_midup ])) if sub_pos == 'lb': rob_x = robin[0][0] rob_y = robin[0][1] ha = 'left' va = 'bottom' elif sub_pos == 'lm': rob_x = robin[1][0] rob_y = robin[1][1] ha = 'left' va = 'center' elif sub_pos == 'lm2': rob_x = robin[8][0] rob_y = robin[8][1] ha = 'left' va = 'center' elif sub_pos == 'lt': rob_x = robin[2][0] rob_y = robin[2][1] ha = 'left' va = 'top' elif sub_pos == 'mb': rob_x = robin[3][0] rob_y = robin[3][1] ha = 'center' va = 'bottom' elif sub_pos == 'mt': rob_x = robin[4][0] rob_y = robin[4][1] ha = 'center' va = 'top' elif sub_pos == 'rb': rob_x = robin[5][0] rob_y = robin[5][1] ha = 'right' va = 'bottom' elif sub_pos == 'rm': rob_x = robin[6][0] rob_y = robin[6][1] ha = 'right' va = 'center' elif sub_pos == 'rt': rob_x = robin[7][0] rob_y = robin[7][1] ha = 'right' va = 'top' if sub_pos[0] == 'r': rob_x = rob_x - 50000 elif sub_pos[0] == 'l': rob_x = rob_x + 50000 if sub_pos[1] == 'b': rob_y = rob_y + 50000 elif sub_pos[1] == 't': rob_y = rob_y - 50000 sub_ax_3 = fig.add_axes(position, projection=ccrs.Robinson(), label=label + 'markup2') # sub_ax_3.add_patch(mpatches.Rectangle((rob_x, rob_y), size_x, size_y , linewidth=1, edgecolor='grey', facecolor='white',transform=ccrs.Robinson())) sub_ax_3.set_extent(extent, ccrs.Geodetic()) verts = mpath.Path(rect_units_to_verts([rob_x, rob_y, size_x, size_y])) sub_ax_3.set_boundary(verts, transform=sub_ax.transAxes) sub_ax_3.text(rob_x, rob_y, markup_sub, horizontalalignment=ha, verticalalignment=va, transform=ccrs.Robinson(), color='black', fontsize=4.5, bbox=dict(facecolor='white', alpha=1, linewidth=0.35, pad=1.5), fontweight='bold', zorder=25) if not main: sub_ax.outline_patch.set_edgecolor('white') else: sub_ax.outline_patch.set_edgecolor('lightgrey')
def MapThatShit(NDAI_BASE, date, spl_arr, drought_avg_tci_cmap): # get array informaiton extent, img_extent = setMap(NDAI_BASE) ds = gdal.Open(NDAI_BASE) array = ds.ReadAsArray() #array[ma.getmaskarray(NDAI)] = 0 #nan = ds.GetRasterBand(1).GetNoDataValue() array = ma.masked_equal(array, 0) array = np.flipud(array) logging.info(extent) # set shape of figure width = array.shape[0] height = array.shape[1] base_width = 10. base_height = (base_width * height) / width print base_width, base_height logging.info(base_width, base_height) # figure fig = plt.figure(figsize=(base_height, base_width)) ax = plt.subplot(1, 1, 1, projection=ccrs.PlateCarree()) ax.set_extent(extent, ccrs.Geodetic()) gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, linewidth=1, color='gray', alpha=0.5, linestyle='--') gl.ylabels_right = False gl.xlabels_top = False # prulletaria on the map ogr2ogr = r'C:\Program Files\GDAL//ogr2ogr.exe' base_geom = r'D:\Data\ChinaShapefile\natural_earth' # ocean in_file_ocean = base_geom + '\physical//10m_ocean.shp' outfile_ocean = 'ocean.shp' # country boudaries in_file_bound = base_geom + '\cultural//10m_admin_0_boundary_lines_land.shp' outfile_bound = 'boundaries.shp' # costlie in_file_coast = base_geom + '\physical//10m_coastline.shp' outfile_coast = 'coastline.shp' #lakes in_file_lakes = base_geom + '\physical//10m_lakes.shp' outfile_lakes = 'lakes.shp' # run the clip functions command = [ ogr2ogr, '-f', "ESRI Shapefile", outfile_ocean, in_file_ocean, '-clipsrc', str(spl_arr[0]), str(spl_arr[1]), str(spl_arr[2]), str(spl_arr[3]), '-overwrite' ] print(sp.list2cmdline(command)) norm = sp.Popen(sp.list2cmdline(command), stdout=sp.PIPE, shell=True) norm.communicate() command = [ ogr2ogr, '-f', "ESRI Shapefile", outfile_bound, in_file_bound, '-clipsrc', str(spl_arr[0]), str(spl_arr[1]), str(spl_arr[2]), str(spl_arr[3]), '-overwrite' ] print(sp.list2cmdline(command)) norm = sp.Popen(sp.list2cmdline(command), stdout=sp.PIPE, shell=True) norm.communicate() command = [ ogr2ogr, '-f', "ESRI Shapefile", outfile_coast, in_file_coast, '-clipsrc', str(spl_arr[0]), str(spl_arr[1]), str(spl_arr[2]), str(spl_arr[3]), '-overwrite' ] print(sp.list2cmdline(command)) norm = sp.Popen(sp.list2cmdline(command), stdout=sp.PIPE, shell=True) norm.communicate() command = [ ogr2ogr, '-f', "ESRI Shapefile", outfile_lakes, in_file_lakes, '-clipsrc', str(spl_arr[0]), str(spl_arr[1]), str(spl_arr[2]), str(spl_arr[3]), '-overwrite' ] print(sp.list2cmdline(command)) norm = sp.Popen(sp.list2cmdline(command), stdout=sp.PIPE, shell=True) norm.communicate() ax.add_geometries(Reader(outfile_ocean).geometries(), ccrs.PlateCarree(), facecolor='lightblue') ax.add_geometries(Reader(outfile_bound).geometries(), ccrs.PlateCarree(), facecolor='', linestyle=':', linewidth=2) ax.add_geometries(Reader(outfile_coast).geometries(), ccrs.PlateCarree(), facecolor='') ax.add_geometries(Reader(outfile_lakes).geometries(), ccrs.PlateCarree(), facecolor='lightskyblue') # ticks of classes bounds = [ 0., 82.875, 95.625, 108.375, 127.5, 146.625, 159.375, 172.125, 255. ] # ticklabels plus colorbar ticks = [ '-1', '-0.35', '-0.25', '-0.15', '+0', '+.15', '+.25', '+.35', '+1' ] cmap = cmap_discretize(drought_avg_tci_cmap, 8) norm = matplotlib.colors.BoundaryNorm(bounds, cmap.N) im = ax.imshow(array, origin='upper', extent=img_extent, norm=norm, cmap=cmap, vmin=0, vmax=255, interpolation='nearest') #, transform=ccrs.Mercator()) title = 'NDAI ' + date plt.title(title, fontsize=22) cb = plt.colorbar(im, fraction=0.0476, pad=0.04, ticks=bounds, norm=norm, orientation='horizontal') cb.set_label('Normalized Drought Anomaly Index') cb.set_ticklabels(ticks) # spl_arr_str = str(spl_arr) # spl_arr_str = spl_arr_str.replace('[','') # spl_arr_str = spl_arr_str.replace(']','') # spl_arr_str = spl_arr_str.replace(', ','#') # spl_arr_str = spl_arr_str.replace('.','.') # and save the shit # outpath = 'NDAI_'+date+'_'+spl_arr_str+'.png' outpath = 'NDAI_' + date + '.png' plt.savefig(outpath, dpi=200, bbox_inches='tight') print outpath logging.info(outpath) #plt.tight_layout() plt.show() plt.close(fig) fig.clf() return outpath
def plot_ppi_map( self, field, sweep=0, mask_tuple=None, vmin=None, vmax=None, cmap=None, norm=None, mask_outside=False, title=None, title_flag=True, colorbar_flag=True, colorbar_label=None, ax=None, fig=None, lat_lines=None, lon_lines=None, projection=None, min_lon=None, max_lon=None, min_lat=None, max_lat=None, width=None, height=None, lon_0=None, lat_0=None, resolution='110m', shapefile=None, shapefile_kwargs=None, edges=True, gatefilter=None, filter_transitions=True, embelish=True, ticks=None, ticklabs=None): """ Plot a PPI volume sweep onto a geographic map. Parameters ---------- field : str Field to plot. sweep : int, optional Sweep number to plot. Other Parameters ---------------- mask_tuple : (str, float) Tuple containing the field name and value below which to mask field prior to plotting, for example to mask all data where NCP < 0.5 set mask_tuple to ['NCP', 0.5]. None performs no masking. vmin : float Luminance minimum value, None for default value. Parameter is ignored is norm is not None. vmax : float Luminance maximum value, None for default value. Parameter is ignored is norm is not None. norm : Normalize or None, optional matplotlib Normalize instance used to scale luminance data. If not None the vmax and vmin parameters are ignored. If None, vmin and vmax are used for luminance scaling. cmap : str or None Matplotlib colormap name. None will use the default colormap for the field being plotted as specified by the Py-ART configuration. mask_outside : bool True to mask data outside of vmin, vmax. False performs no masking. title : str Title to label plot with, None to use default title generated from the field and tilt parameters. Parameter is ignored if title_flag is False. title_flag : bool True to add a title to the plot, False does not add a title. colorbar_flag : bool True to add a colorbar with label to the axis. False leaves off the colorbar. ticks : array Colorbar custom tick label locations. ticklabs : array Colorbar custom tick labels. colorbar_label : str Colorbar label, None will use a default label generated from the field information. ax : Cartopy GeoAxes instance If None, create GeoAxes instance using other keyword info. If provided, ax must have a Cartopy crs projection and projection kwarg below is ignored. fig : Figure Figure to add the colorbar to. None will use the current figure. lat_lines, lon_lines : array or None Locations at which to draw latitude and longitude lines. None will use default values which are resonable for maps of North America. projection : cartopy.crs class Map projection supported by cartopy. Used for all subsequent calls to the GeoAxes object generated. Defaults to LambertConformal centered on radar. min_lat, max_lat, min_lon, max_lon : float Latitude and longitude ranges for the map projection region in degrees. width, height : float Width and height of map domain in meters. Only this set of parameters or the previous set of parameters (min_lat, max_lat, min_lon, max_lon) should be specified. If neither set is specified then the map domain will be determined from the extend of the radar gate locations. shapefile : str Filename for a shapefile to add to map. shapefile_kwargs : dict Key word arguments used to format shapefile. Projection defaults to lat lon (cartopy.crs.PlateCarree()) resolution : '10m', '50m', '110m'. Resolution of NaturalEarthFeatures to use. See Cartopy documentation for details. gatefilter : GateFilter GateFilter instance. None will result in no gatefilter mask being applied to data. filter_transitions : bool True to remove rays where the antenna was in transition between sweeps from the plot. False will include these rays in the plot. No rays are filtered when the antenna_transition attribute of the underlying radar is not present. edges : bool True will interpolate and extrapolate the gate edges from the range, azimuth and elevations in the radar, treating these as specifying the center of each gate. False treats these coordinates themselved as the gate edges, resulting in a plot in which the last gate in each ray and the entire last ray are not not plotted. embelish: bool True by default. Set to False to supress drawing of coastlines etc.. Use for speedup when specifying shapefiles. Note that lat lon labels only work with certain projections. """ # parse parameters ax, fig = parse_ax_fig(ax, fig) vmin, vmax = parse_vmin_vmax(self._radar, field, vmin, vmax) cmap = parse_cmap(cmap, field) if lat_lines is None: lat_lines = np.arange(30, 46, 1) if lon_lines is None: lon_lines = np.arange(-110, -75, 1) lat_0 = self.loc[0] lon_0 = self.loc[1] # get data for the plot data = self._get_data( field, sweep, mask_tuple, filter_transitions, gatefilter) x, y = self._get_x_y(sweep, edges, filter_transitions) # mask the data where outside the limits if mask_outside: data = np.ma.masked_outside(data, vmin, vmax) # initialize instance of GeoAxes if not provided if hasattr(ax, 'projection'): projection = ax.projection else: if projection is None: # set map projection to LambertConformal if none is specified projection = cartopy.crs.LambertConformal( central_longitude=lon_0, central_latitude=lat_0) ax = plt.axes(projection=projection) if min_lon: ax.set_extent([min_lon, max_lon, min_lat, max_lat], crs=cartopy.crs.PlateCarree()) elif width: ax.set_extent([-width/2., width/2., -height/2., height/2.], crs=self.grid_projection) # plot the data if norm is not None: # if norm is set do not override with vmin/vmax vmin = vmax = None pm = ax.pcolormesh(x * 1000., y * 1000., data, vmin=vmin, vmax=vmax, cmap=cmap, norm=norm, transform=self.grid_projection) # add embelishments if embelish is True: # Create a feature for States/Admin 1 regions at 1:resolution # from Natural Earth states_provinces = cartopy.feature.NaturalEarthFeature( category='cultural', name='admin_1_states_provinces_lines', scale=resolution, facecolor='none') ax.coastlines(resolution=resolution) ax.add_feature(states_provinces, edgecolor='gray') # labeling gridlines poses some difficulties depending on the # projection, so we need some projection-spectific methods if ax.projection in [cartopy.crs.PlateCarree(), cartopy.crs.Mercator()]: gl = ax.gridlines(xlocs=lon_lines, ylocs=lat_lines, draw_labels=True) gl.xlabels_top = False gl.ylabels_right = False elif isinstance(ax.projection, cartopy.crs.LambertConformal): fig.canvas.draw() ax.gridlines(xlocs=lon_lines, ylocs=lat_lines) # Label the end-points of the gridlines using the custom # tick makers: ax.xaxis.set_major_formatter( cartopy.mpl.gridliner.LONGITUDE_FORMATTER) ax.yaxis.set_major_formatter( cartopy.mpl.gridliner.LATITUDE_FORMATTER) if _LAMBERT_GRIDLINES: lambert_xticks(ax, lon_lines) lambert_yticks(ax, lat_lines) else: ax.gridlines(xlocs=lon_lines, ylocs=lat_lines) # plot the data and optionally the shape file # we need to convert the radar gate locations (x and y) which are in # km to meters we also need to give the original projection of the # data which is stored in self.grid_projection if shapefile is not None: from cartopy.io.shapereader import Reader if shapefile_kwargs is None: shapefile_kwargs = {} if 'crs' not in shapefile_kwargs: shapefile_kwargs['crs'] = cartopy.crs.PlateCarree() ax.add_geometries(Reader(shapefile).geometries(), **shapefile_kwargs) if title_flag: self._set_title(field, sweep, title, ax) # add plot and field to lists self.plots.append(pm) self.plot_vars.append(field) if colorbar_flag: self.plot_colorbar( mappable=pm, label=colorbar_label, field=field, fig=fig, ax=ax, ticks=ticks, ticklabs=ticklabs) # keep track of this GeoAxes object for later self.ax = ax return
def cartoplot_sf_price(data, mapsize, pricequintiles, shapefile): # Create a Stamen terrain background instance stamen_terrain = cimgt.Stamen('terrain-background') fig = plt.figure(figsize=(mapsize, mapsize)) ax = fig.add_subplot(1, 1, 1, projection=stamen_terrain.crs) # Set range of map, stipulate zoom level ax.set_extent([-122.55, -122.35, 37.7, 37.835], crs=ccrs.Geodetic()) ax.add_image(stamen_terrain, 14) # Add city borders shape_feature = ShapelyFeature(Reader(shapefile).geometries(), ccrs.Geodetic(), linewidth=1, facecolor=(1, 1, 1, 0), edgecolor=(0.3, 0.3, 0.3, 1)) ax.add_feature(shape_feature, zorder=1) # Determine plotting mode and subdivide data based on quintiles q1 = data.loc[data['Price'] < pricequintiles[0]] q2 = data.loc[(data['Price'] > pricequintiles[0]) & (data['Price'] < pricequintiles[1])] q3 = data.loc[(data['Price'] > pricequintiles[1]) & (data['Price'] < pricequintiles[2])] q4 = data.loc[(data['Price'] > pricequintiles[2]) & (data['Price'] < pricequintiles[3])] q5 = data.loc[data['Price'] > pricequintiles[3]] # Create legend labels l1 = '< $%s M' % str(round(pricequintiles[0] / 1000000, 2)) l2 = '\$%s M to $%s M' % (round(pricequintiles[0] / 1000000, 2), round(pricequintiles[1] / 1000000, 2)) l3 = '\$%s M to $%s M' % (round(pricequintiles[1] / 1000000, 2), round(pricequintiles[2] / 1000000, 2)) l4 = '\$%s M to $%s M' % (round(pricequintiles[2] / 1000000, 2), round(pricequintiles[3] / 1000000, 2)) l5 = '> $%s M' % str(round(pricequintiles[3] / 1000000, 2)) # Plot scatter based on price quintiles ax.scatter(q1['Longitude'], q1['Latitude'], s=75, zorder=2, c='darkred', edgecolors='black', transform=ccrs.PlateCarree(), label=l1) ax.scatter(q2['Longitude'], q2['Latitude'], s=75, zorder=2, c='salmon', edgecolors='black', transform=ccrs.PlateCarree(), label=l2) ax.scatter(q3['Longitude'], q3['Latitude'], s=75, zorder=2, c='grey', edgecolors='black', transform=ccrs.PlateCarree(), label=l3) ax.scatter(q4['Longitude'], q4['Latitude'], s=75, zorder=2, c='cornflowerblue', edgecolors='black', transform=ccrs.PlateCarree(), label=l4) ax.scatter(q5['Longitude'], q5['Latitude'], s=75, zorder=2, c='darkblue', edgecolors='black', transform=ccrs.PlateCarree(), label=l5) # Add text box to map lgnd = ax.legend(loc=2, prop={'size': 25}, title=r'$\bf{San\/Francisco\/\/}$', title_fontsize=30) #change the marker size manually for both lines lgnd.legendHandles[0]._sizes = [150] lgnd.legendHandles[1]._sizes = [150] lgnd.legendHandles[2]._sizes = [150] lgnd.legendHandles[3]._sizes = [150] lgnd.legendHandles[4]._sizes = [150] plt.show()
import cartopy.crs as ccrs import matplotlib.pyplot as plt import io import json import pickle south_china_sea = 3415 crs = ccrs.Mercator() crs2 = ccrs.epsg(3415) crs = ccrs.Mercator() fig = plt.figure(figsize=(20, 20)) ax = fig.add_subplot(1, 1, 1, projection=crs) #ax = plt.axes(projection=crs) #ax.set_extent([140, 80, -2, 55], crs=crs) ax.set_extent([136, 72, 3, 55], crs=crs) world = Reader(path_join('Basemap', 'world')) nation = Reader(path_join('Basemap', 'nation')) province = Reader(path_join('Basemap', 'province')) river = Reader(path_join('Basemap', 'river')) lake = Reader(path_join('Basemap', 'lake')) ax.add_geometries(world.geometries(), crs=crs, edgecolor='#555555', facecolor='none', linewidth=1.5) ax.add_geometries(nation.geometries(), crs=crs, edgecolor='#000000', facecolor='none', linewidth=2) ax.add_geometries(province.geometries(),
import data_utils as du from namelist import * latlim = [24, 60]; lonlim = [-150, -100] dx = 0.25; dy = 0.25 lon_025, lat_025 = np.meshgrid(np.arange(lonlim[0], lonlim[1]+dx, dx), np.arange(latlim[0], latlim[1]+dy, dy)) dx = 0.0416666666666; dy = 0.0416666666666 lon_4km, lat_4km = np.meshgrid(np.arange(lonlim[0], lonlim[1]+dx, dx), np.arange(latlim[0], latlim[1]+dy, dy)) import shapely import cartopy.io.shapereader as shpreader from cartopy.io.shapereader import Reader shpfilename = shpreader.natural_earth(resolution='110m', category='physical', name='ocean') land_shp = Reader(shpfilename) shape_4km = lon_4km.shape land_id = np.ones(shape_4km)*np.nan for i in range(shape_4km[0]): for j in range(shape_4km[1]): temp_point = shapely.geometry.Point(lon_4km[i, j], lat_4km[i, j]) for n, shp in enumerate(land_shp.records()): if shp.geometry.contains(temp_point): land_id[i, j] = n land_mask = ~np.isnan(land_id) # ETOPO interp print('Process ETOPO') with nc.Dataset(BACKUP_dir+'ETOPO1_Ice_g_gmt4.grd') as nc_obj:
def plot_measurement_stations(image_path, image_2path, coastline_path, river_path, figsz, lon_min_MOD, lon_max_MOD, lat_min_MOD, lat_max_MOD, sis_color, obt_color, fontsz): ''' Function to plot simple map of the locations and deployment durations of the OBT and SIS ''' gdal.UseExceptions() coastline = ShapelyFeature(Reader(coastline_path).geometries(),ccrs.PlateCarree()) river = ShapelyFeature(Reader(river_path).geometries(),ccrs.PlateCarree()) #open tiff file and extract data, geotransform, and crs ds = gdal.Open(image_path) data = ds.ReadAsArray() gt = ds.GetGeoTransform() proj = ds.GetProjection() inproj = osr.SpatialReference() inproj.ImportFromWkt(proj) projcs = inproj.GetAuthorityCode('PROJCS') projection = ccrs.epsg(projcs) subplot_kw = dict(projection=projection) #initialize figure fig, axx = plt.subplots(figsize=figsz, subplot_kw=subplot_kw) extent = (gt[0], gt[0] + ds.RasterXSize * gt[1], gt[3] + ds.RasterYSize * gt[5], gt[3]) img = axx.imshow(data[:3, :, :].transpose((1, 2, 0)), extent=extent, origin='upper') axx.set_extent([lon_min_MOD, lon_max_MOD, lat_min_MOD, lat_max_MOD]) plot_MODIS_geotiff(axx,image_2path, coastline, lon_min_MOD, lon_max_MOD, lat_min_MOD, lat_max_MOD) #add coastlines and features axx.add_feature(coastline,zorder=300, edgecolor='k', facecolor='#efebd3', alpha=1) axx.add_feature(river,zorder=350, edgecolor='#46d3f6', facecolor='none', alpha=1,linewidth=4) #add title to map axx.text(0.5, 0.99, 'Measurement Stations \n in Kotzebue Sound', fontsize=45, fontname='Calibri', horizontalalignment='center', verticalalignment='top', transform=axx.transAxes, bbox=dict(boxstyle='square,pad=0.15', facecolor='w', alpha=0.8),zorder=400) #add data source to map axx.text(0.006, 0.01, ' Satellite Image From \n MODIS Visible, \n May 7 2019', fontsize=18, fontname='Calibri', horizontalalignment='left', verticalalignment='bottom', transform=axx.transAxes, bbox=dict(boxstyle='square,pad=0.15', facecolor='w', alpha=0.8),zorder=400) #add circles axx.add_patch(patches.Ellipse(xy=(-162.6139,66.8968), width=0.1, height=0.04, edgecolor=sis_color, linewidth=6, transform=ccrs.PlateCarree(), facecolor='none',zorder=400)); axx.add_patch(patches.Ellipse(xy=(-163.7957,67.0598), width=0.1, height=0.04, edgecolor=obt_color, linewidth=6, transform=ccrs.PlateCarree(), facecolor='none',zorder=400)); axx.text(0.57, 0.53, 'ITO', fontsize=fontsz, fontname='Calibri', horizontalalignment='left', verticalalignment='center', transform=axx.transAxes, bbox=dict(boxstyle='square,pad=0.3', facecolor=sis_color, edgecolor='k', linewidth=3,alpha=1),zorder=400) axx.text(0.57, 0.47, 'Jan 2019 - Apr 2019', fontsize=fontsz-2, fontname='Calibri', horizontalalignment='left', verticalalignment='center', transform=axx.transAxes, bbox=dict(boxstyle='square,pad=0.3', facecolor=sis_color, edgecolor='k', linewidth=3,alpha=1),zorder=400) axx.text(0.57, 0.41, '66.8968 N, 162.6139 W', fontsize=fontsz-2, fontname='Calibri', horizontalalignment='left', verticalalignment='center', transform=axx.transAxes, bbox=dict(boxstyle='square,pad=0.3', facecolor=sis_color, edgecolor='k', linewidth=3,alpha=1),zorder=400) axx.text(0.3, 0.66, 'OBT', fontsize=fontsz, fontname='Calibri', horizontalalignment='right', verticalalignment='center', transform=axx.transAxes, bbox=dict(boxstyle='square,pad=0.3', facecolor=obt_color, edgecolor='k', linewidth=3,alpha=1),zorder=400) axx.text(0.3, 0.6, 'Sep 2017 - Jun 2019', fontsize=fontsz-2, fontname='Calibri', horizontalalignment='right', verticalalignment='center', transform=axx.transAxes, bbox=dict(boxstyle='square,pad=0.3', facecolor=obt_color, edgecolor='k', linewidth=3,alpha=1),zorder=400) axx.text(0.3, 0.54, '67.0598 N, 163.7957 W', fontsize=fontsz-2, fontname='Calibri', horizontalalignment='right', verticalalignment='center', transform=axx.transAxes, bbox=dict(boxstyle='square,pad=0.3', facecolor=obt_color, edgecolor='k', linewidth=3,alpha=1),zorder=400)
def get_geometries_countries(country_names): print(country_names) """ Get an iterable of Shapely geometries corrresponding to given countries. """ if country_names == 'NorthChina': country_names2 = ['China'] elif country_names == 'SouthChina': country_names2 = ['China', 'Taiwan'] elif country_names == 'JapanKorea': country_names2 = ['Japan', 'Republic of Korea', 'Dem. Rep. Korea'] elif country_names == 'NorthAsia': country_names2 = ['Russian Federation', 'Mongolia', 'Kazakhstan'] elif country_names == 'IndianSub': country_names2 = ['India', 'Nepal', 'Bhutan', 'Sri Lanka'] elif country_names == 'MiddleEast': country_names2 = [ 'Jordan', 'Israel', 'Saudi Arabia', 'Yemen', 'Oman', 'Lebanon', 'Iraq', 'Syria', 'United Arab Emirates', 'Kuwait' ] elif country_names == 'WestAsia': country_names2 = [ 'Iran', 'Afghanistan', 'Turkmenistan', 'Uzbekistan', 'Tajikistan', 'Kyrgyzstan', 'Azerbaijan', 'Georgia', 'Armenia' ] elif country_names == 'IndoMalaysia': country_names2 = ['Indonesia', 'Malaysia', 'Singapour'] elif country_names == 'Europe': country_names2= ['Italy','France','Greece','Macedonia','Albania','Montenegro','Kosovo','Bulgaria','Serbia','Romania',\ 'Bosnia and Herzegovina','Slovenia','Hungary','Croatia','Slovakia','Austria','Czech Republic','Cyprus',\ 'Poland','Ukraine','Belarus','Moldova','Lithuania','Latvia','Estonia','Germany','Spain','Belgium','Switzerland',\ 'Northern Cyprus','Denmark','Finland','Georgia','Luxembourg','Norway','Sweden','Turkey','Portugal'] else: country_names2 = country_names # Using the Natural Earth feature interface provided by cartopy. # You could use a different source, all you need is the geometries. shape_records = Reader( natural_earth(resolution='110m', category='cultural', name='admin_0_countries')).records() geoms = [] names = [] for country in shape_records: if country.attributes['NAME_LONG'] in country_names2: try: print('processing', country.attributes['NAME_LONG']) geoms += country.geometry except TypeError: geoms.append(country.geometry) for i in range(len(country.geometry)): names.append(country_names) return geoms, ccrs.PlateCarree()._as_mpl_transform, names
# lats = f['XLAT'].values[0] # lons = f['XLONG'].values[0] lats = f.variables['XLAT'][0] lons = f.variables['XLONG'][0] # lats, lons = latlon_coords(rainc) cart_proj = get_cartopy(rainc) # print(cart_proj) levels = [0.1, 0.5, 1., 2., 3., 4., 5., 6., 8., 10., 20., 40] norm = colors.BoundaryNorm(boundaries=np.array(levels), ncolors=len(levels) - 1) shp_path = '/Users/james/Documents/GitHub/py_china_shp/' reader = Reader(shp_path + 'Province_9/Province_9.shp') provinces = cfe.ShapelyFeature(reader.geometries(), ccrs.PlateCarree(), edgecolor='k', facecolor='none') with PdfPages('multipage_pdf.pdf') as pdf: for i in range(3): fig = plt.figure(figsize=(14, 8.5)) ax = fig.add_subplot(111, projection=cart_proj) print(ax) ax.add_feature(provinces, linewidth=0.6) ax.coastlines('50m', linewidth=0.8) pcm = ax.contourf(lons,
def plot_layered_landfast_ice_map(data_folder, coastline_path, river_path, kotz_path, transparency, xmin, xmax, ymin, ymax, plotflag): ''' This function imports shapefiles of landfast ice extent and plots them in a transparent stack with 2019 in red, along with coastline and river shapefiles and some labels and legends. Inputs: ''' #define colors (could be made an input) seacolor='#121b86' colorstring='#ffffff' color2019='#bc112b' #Underlying rectangle for legend of blue with transparent boxes stacked on top. Need 20 boxes to account for 19 years + the zero value. x = 0.89 y = 0.54 w = 0.025 h = 0.35 nyears = 20 #read in shapefiles coastline = ShapelyFeature(Reader(coastline_path).geometries(),ccrs.PlateCarree()) river = ShapelyFeature(Reader(river_path).geometries(),ccrs.PlateCarree()) kotz = ShapelyFeature(Reader(kotz_path).geometries(),ccrs.PlateCarree()) shape_list = [] files = glob.glob(data_folder + '\*.shp') for fname in files: shape_feature = ShapelyFeature(Reader(fname).geometries(),ccrs.PlateCarree(), edgecolor='black', facecolor=colorstring, alpha=transparency) shape_list.append(shape_feature) lfi2019_feature = ShapelyFeature(Reader(fname).geometries(),ccrs.PlateCarree(), edgecolor='black', facecolor=color2019, alpha=1) #initialize map figure fig,axx = plt.subplots(figsize=(16,16),subplot_kw=dict(projection=ccrs.AlbersEqualArea(central_longitude=(xmin+xmax)/2,central_latitude=(ymin+ymax)/2,standard_parallels=[40,65]))) #put in background color of #121b86 axx.background_patch.set_facecolor(seacolor) #set map extent axx.set_extent([xmin,xmax,ymin,ymax]) #stack layers of transparent ice shapes yr = 2000 for shape in shape_list: axx.add_feature(shape) #if we want to save a plot of every year... if plotflag == 1: #add coastline shapefile axx.add_feature(coastline,zorder=300, edgecolor='k', facecolor='#efebd3', alpha=1) #add rivers shapefile axx.add_feature(river,zorder=350, edgecolor='#46d3f6', facecolor='#efebd3', alpha=1,linewidth=4) #Add title to map #axx.text(0.5, 0.99, 'Landfast Ice Extent \n Since 2000', fontsize=45, fontname='Calibri', horizontalalignment='center', verticalalignment='top', transform=axx.transAxes, # bbox=dict(boxstyle='square,pad=0.15', facecolor='w', alpha=0.8),zorder=400) #Add data source to map #axx.text(0.006, 0.01, 'Ice Edges Traced from MODIS Visible Images', fontsize=18, fontname='Calibri', horizontalalignment='left', verticalalignment='bottom', transform=axx.transAxes, # bbox=dict(boxstyle='square,pad=0.15', facecolor='w', alpha=0.8),zorder=400) #Add custom legend to map #plot legend boxes axx.add_patch(patches.Rectangle(xy=(x,y), width=w, height=h, edgecolor='k', facecolor=seacolor, alpha=1, transform=axx.transAxes, zorder=400)) for idx in np.arange(1,nyears): counter = 0 while counter < idx: axx.add_patch(patches.Rectangle(xy=(x,y+(idx*h/nyears)), width=w, height=h/nyears, edgecolor='k', facecolor=colorstring, alpha=0.15, transform=axx.transAxes, zorder=400)) counter = counter + 1 #label legend axx.text(x, y + h, '% of Prior Years \n (2000-2018) \n Covered By \n Landfast Ice ', fontsize=20, fontname='Calibri', horizontalalignment='right', verticalalignment='top', transform=axx.transAxes,zorder=400) axx.text(x + w, y + h, ' 100%', fontsize=20, fontname='Calibri', horizontalalignment='left', verticalalignment='top', transform=axx.transAxes,zorder=400) axx.text(x + w, y + h/2, ' 50%', fontsize=20, fontname='Calibri', horizontalalignment='left', verticalalignment='center', transform=axx.transAxes,zorder=400) axx.text(x + w, y - (h/nyears/2), ' 0%', fontsize=20, fontname='Calibri', horizontalalignment='left', verticalalignment='bottom', transform=axx.transAxes,zorder=400) #add 2019 to legend #axx.add_patch(patches.Rectangle(xy=(x,y+h+(2*h/nyears)), width=w, height=h/nyears, edgecolor='k', facecolor=color2019, alpha=1, transform=axx.transAxes, zorder=400)) #axx.text(x, y + h +(2.4*h/nyears), '2019 ', fontsize=20, fontname='Calibri', horizontalalignment='right', verticalalignment='center', transform=axx.transAxes,zorder=400) #label features on plot axx.text(0.7, 0.475, 'Kobuk \n River', fontsize=18, transform=axx.transAxes, zorder=400) axx.text(0.46, 0.75, 'Noatak \n River', fontsize=18, transform=axx.transAxes, zorder=400) axx.text(0.538, 0.545, 'Kotzebue', fontsize=13, transform=axx.transAxes, zorder=400) axx.add_patch(patches.Arrow(x=0.55, y=0.56, dx=-0.016, dy=0.03, width=0.01, facecolor='k',transform=axx.transAxes,zorder=400)); plt.savefig(f'Figures/Layered Landfast Ice Maps/LandfastIce_to_{yr}.png',dpi=300,facecolor='k') yr = yr + 1 #add 2019 in red axx.add_feature(lfi2019_feature) #add coastline shapefile axx.add_feature(coastline,zorder=300, edgecolor='k', facecolor='#efebd3', alpha=1) #add rivers shapefile axx.add_feature(river,zorder=350, edgecolor='#46d3f6', facecolor='#efebd3', alpha=1,linewidth=4) #Add title to map axx.text(0.5, 0.99, 'Landfast Ice Extent \n Since 2000', fontsize=45, fontname='Calibri', horizontalalignment='center', verticalalignment='top', transform=axx.transAxes, bbox=dict(boxstyle='square,pad=0.15', facecolor='w', alpha=0.8),zorder=400) #Add data source to map axx.text(0.006, 0.01, 'Ice Edges Traced from MODIS Visible Images', fontsize=18, fontname='Calibri', horizontalalignment='left', verticalalignment='bottom', transform=axx.transAxes, bbox=dict(boxstyle='square,pad=0.15', facecolor='w', alpha=0.8),zorder=400) #Add custom legend to map #plot legend boxes axx.add_patch(patches.Rectangle(xy=(x,y), width=w, height=h, edgecolor='k', facecolor=seacolor, alpha=1, transform=axx.transAxes, zorder=400)) for idx in np.arange(1,nyears): counter = 0 while counter < idx: axx.add_patch(patches.Rectangle(xy=(x,y+(idx*h/nyears)), width=w, height=h/nyears, edgecolor='k', facecolor=colorstring, alpha=0.15, transform=axx.transAxes, zorder=400)) counter = counter + 1 #label legend axx.text(x, y + h, '% of Prior Years \n (2000-2018) \n Covered By \n Landfast Ice ', fontsize=20, fontname='Calibri', horizontalalignment='right', verticalalignment='top', transform=axx.transAxes,zorder=400) axx.text(x + w, y + h, ' 100%', fontsize=20, fontname='Calibri', horizontalalignment='left', verticalalignment='top', transform=axx.transAxes,zorder=400) axx.text(x + w, y + h/2, ' 50%', fontsize=20, fontname='Calibri', horizontalalignment='left', verticalalignment='center', transform=axx.transAxes,zorder=400) axx.text(x + w, y - (h/nyears/2), ' 0%', fontsize=20, fontname='Calibri', horizontalalignment='left', verticalalignment='bottom', transform=axx.transAxes,zorder=400) #add 2019 to legend axx.add_patch(patches.Rectangle(xy=(x,y+h+(2*h/nyears)), width=w, height=h/nyears, edgecolor='k', facecolor=color2019, alpha=1, transform=axx.transAxes, zorder=400)) axx.text(x, y + h +(2.4*h/nyears), '2019 ', fontsize=20, fontname='Calibri', horizontalalignment='right', verticalalignment='center', transform=axx.transAxes,zorder=400) #label features on plot axx.text(0.7, 0.475, 'Kobuk \n River', fontsize=18, transform=axx.transAxes, zorder=400) axx.text(0.46, 0.75, 'Noatak \n River', fontsize=18, transform=axx.transAxes, zorder=400) axx.text(0.538, 0.545, 'Kotzebue', fontsize=13, transform=axx.transAxes, zorder=400) axx.add_patch(patches.Arrow(x=0.55, y=0.56, dx=-0.016, dy=0.03, width=0.01, facecolor='k',transform=axx.transAxes,zorder=400)); axx.text(0.345, 0.127, '2006', fontsize=14, transform=axx.transAxes, zorder=400) axx.text(0.354, 0.153, '2018', fontsize=14, transform=axx.transAxes, zorder=400) axx.text(0.363, 0.19, '2011', fontsize=14, transform=axx.transAxes, zorder=400) axx.text(0.375, 0.23, '2009', fontsize=14, transform=axx.transAxes, zorder=400) axx.text(0.4, 0.285, '2004', fontsize=14, transform=axx.transAxes, zorder=400) axx.text(0.44, 0.43, '2014', fontsize=14, transform=axx.transAxes, zorder=400) axx.text(0.355, 0.47, '2017', fontsize=14, transform=axx.transAxes, zorder=400) axx.text(-0.065, 0.01, '$66.0^\circ$N', fontsize=14, transform=axx.transAxes, zorder=400) axx.text(-0.065, 0.34, '$66.5^\circ$N', fontsize=14, transform=axx.transAxes, zorder=400) axx.text(-0.065, 0.67, '$67.0^\circ$N', fontsize=14, transform=axx.transAxes, zorder=400) axx.text(-0.065, 0.97, '$67.5^\circ$N', fontsize=14, transform=axx.transAxes, zorder=400) axx.text(0.06,-0.025, '$165^\circ$W', fontsize=14, transform=axx.transAxes, zorder=400) axx.text(0.43,-0.025, '$163^\circ$W', fontsize=14, transform=axx.transAxes, zorder=400) axx.text(0.8,-0.025, '$161^\circ$W', fontsize=14, transform=axx.transAxes, zorder=400) #plot urban Kotzebue axx.add_feature(kotz,zorder=300, edgecolor='k', facecolor='gray', alpha=1) #plot circles for locations of ITO and OBT from matplotlib.patches import Ellipse ITO_xy = (-162.6170,66.8969) OBT_xy = (-163.7957,67.0598) wd = 0.05 axx.add_patch(Ellipse(xy=ITO_xy,width=wd,height=wd/2.5,transform=ccrs.PlateCarree(),zorder=500,facecolor='w',edgecolor='k')) axx.text(0.498, 0.598, 'ITO', fontsize=13, transform=axx.transAxes, zorder=400) axx.add_patch(Ellipse(xy=OBT_xy,width=wd,height=wd/2.5,transform=ccrs.PlateCarree(),zorder=500,color='k')) axx.text(0.278, 0.7, 'OBT', fontsize=13, transform=axx.transAxes, zorder=400)
''' set the map, with etopo optionally ''' datadir = './' grd = pyroms.grid.get_ROMS_grid(grdname) lonmin = grd.hgrid.lon_rho.min() lonmax = grd.hgrid.lon_rho.max() latmin = grd.hgrid.lat_rho.min() latmax = grd.hgrid.lat_rho.max() plt.figure(figsize=[8., 8.]) ax = plt.axes(projection=ccrs.PlateCarree()) ax.set_extent([lonmin, lonmax, latmin, latmax]) ax.coastlines() return ax ax = setup_map() reader = shpreader.Reader('./data/NEWS2basins.shp') basins = reader.records() basin = next(basins) shape_feature = ShapelyFeature(Reader('./data/NEWS2basins.shp').geometries(), ccrs.PlateCarree(), edgecolor='black') ax.add_feature(shape_feature, facecolor='blue') #print basin plt.show()
# Making a map # values for ploting lat = one_time['lat_0'].values lon = one_time['lon_0'].values precip = one_time.values projection = ccrs.PlateCarree() # start a figure named fig, set axis name, dimesions of fig, and projection fig, ax = plt.subplots(1, 1, figsize=(6, 6), subplot_kw={'projection': projection}) # add .shp file of the catchment shape_feature = ShapelyFeature(Reader(basin_file).geometries(), projection, edgecolor='black', linewidth=1.5, facecolor='none') ax.add_feature(shape_feature) # set up colormap, levels and colorbar intervals cmap = plt.get_cmap('Blues') # pick the desired colormap, levs = np.arange(0, 5, 0.25) # sensible levels, norm = BoundaryNorm(levs, ncolors=cmap.N, clip=True) # draw mesh of data (no contouring with low res data) cs = ax.pcolormesh(lon, lat, precip,
MAIN_PATH, 'input_data/00_rgi50_regions/00_rgi50_O2Regions.shp') filename_coastline = os.path.join( MAIN_PATH, 'input_data/ne_10m_coastline/ne_10m_coastline.shp') mc_nabb = os.path.join(MAIN_PATH, 'input_data/Mcnabb_glaciers/01_rgi50_Alaska.shp') rgi_sub_regions # Reading all the shapefiles #RGI sub-regions dg = gpd.read_file(rgi_sub_regions) #Read hi resolution coast line shape_coast = ShapelyFeature(Reader(filename_coastline).geometries(), ccrs.PlateCarree(), facecolor='none', edgecolor='black') #Read McNabb glaciers dm = gpd.read_file(mc_nabb) dm['centroid_column'] = dm.centroid dm = dm.set_geometry('centroid_column') #RGI v6 df = gpd.read_file(RGI_FILE) df.set_index('RGIId') index = df.index.values #Classify the glaciers
data_crs = cartopy.crs.PlateCarree() fig = plt.figure(figsize=(7, 6), dpi=500) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], projection=plot_crs) blue = '#4b92db' ax.background_patch.set_facecolor(blue) # ax.add_feature(cartopy.feature.LAND) #ax.add_feature(cartopy.feature.OCEAN) ##ax.add_feature(cartopy.feature.COASTLINE) #ax.add_feature(cartopy.feature.BORDERS, linestyle=':') #ax.add_feature(cartopy.feature.LAKES, alpha=0.5) #ax.add_feature(cartopy.feature.RIVERS) ax.set_extent([-82,-32, -45, 10]) ax.set_title('H16 SSM '+str(timestamp.isoformat())) sc = ax.scatter(lons, lats, c=data, zorder=2, marker='s', s=2, transform=data_crs, cmap=smcolormaps.load('SWI_ASCAT'), vmin=0, vmax=100) cax = fig.add_axes([0.92, 0.1, 0.025, 0.8]) cbar = fig.colorbar(sc, cax=cax) cbar.set_label('Degree of Saturation (%)') ax.coastlines() fname = '/home/raja/Downloads/BRA_adm_shp/BRA_adm1' ax.add_geometries(Reader(fname).geometries(), data_crs, facecolor='none', edgecolor='black', zorder=3) fig.savefig("/home/raja/h16_ssm.jpg", bbox_inches = 'tight')
def draw_contour(shakegrid, popgrid, oceanfile, oceangridfile, cityfile, basename, borderfile=None, is_scenario=False): """Create a contour map showing population (greyscale) underneath contoured MMI. :param shakegrid: ShakeGrid object. :param popgrid: Grid2D object containing population data. :param oceanfile: String path to file containing ocean vector data in a format compatible with fiona. :param oceangridfile: String path to file containing ocean grid data . :param cityfile: String path to file containing GeoNames cities data. :param basename: String path containing desired output PDF base name, i.e., /home/pager/exposure. ".pdf" and ".png" files will be made. :param make_png: Boolean indicating whether a PNG version of the file should also be created in the same output folder as the PDF. :returns: Tuple containing: - Name of PNG file created, or None if PNG output not specified. - Cities object containing the cities that were rendered on the contour map. """ gd = shakegrid.getGeoDict() # Retrieve the epicenter - this will get used on the map center_lat = shakegrid.getEventDict()['lat'] center_lon = shakegrid.getEventDict()['lon'] # load the ocean grid file (has 1s in ocean, 0s over land) # having this file saves us almost 30 seconds! oceangrid = GDALGrid.load(oceangridfile, samplegeodict=gd, resample=True) # load the cities data, limit to cities within shakemap bounds allcities = Cities.fromDefault() cities = allcities.limitByBounds((gd.xmin, gd.xmax, gd.ymin, gd.ymax)) # define the map # first cope with stupid 180 meridian height = (gd.ymax-gd.ymin)*111.191 if gd.xmin < gd.xmax: width = (gd.xmax-gd.xmin)*np.cos(np.radians(center_lat))*111.191 xmin, xmax, ymin, ymax = (gd.xmin, gd.xmax, gd.ymin, gd.ymax) else: xmin, xmax, ymin, ymax = (gd.xmin, gd.xmax, gd.ymin, gd.ymax) xmax += 360 width = ((gd.xmax+360) - gd.xmin)*np.cos(np.radians(center_lat))*111.191 aspect = width/height # if the aspect is not 1, then trim bounds in x or y direction as appropriate if width > height: dw = (width - height)/2.0 # this is width in km xmin = xmin + dw/(np.cos(np.radians(center_lat))*111.191) xmax = xmax - dw/(np.cos(np.radians(center_lat))*111.191) width = (xmax-xmin)*np.cos(np.radians(center_lat))*111.191 if height > width: dh = (height - width)/2.0 # this is width in km ymin = ymin + dh/111.191 ymax = ymax - dh/111.191 height = (ymax-ymin)*111.191 aspect = width/height figheight = FIGWIDTH/aspect bbox = (xmin, ymin, xmax, ymax) bounds = (xmin, xmax, ymin, ymax) figsize = (FIGWIDTH, figheight) # Create the MercatorMap object, which holds a separate but identical # axes object used to determine collisions between city labels. mmap = MercatorMap(bounds, figsize, cities, padding=0.5) fig = mmap.figure ax = mmap.axes # this needs to be done here so that city label collision detection will work fig.canvas.draw() clon = xmin + (xmax-xmin)/2 clat = ymin + (ymax-ymin)/2 geoproj = mmap.geoproj proj = mmap.proj # project our population grid to the map projection projstr = proj.proj4_init popgrid_proj = popgrid.project(projstr) popdata = popgrid_proj.getData() newgd = popgrid_proj.getGeoDict() # Use our GMT-inspired palette class to create population and MMI colormaps popmap = ColorPalette.fromPreset('pop') mmimap = ColorPalette.fromPreset('mmi') # set the image extent to that of the data img_extent = (newgd.xmin, newgd.xmax, newgd.ymin, newgd.ymax) plt.imshow(popdata, origin='upper', extent=img_extent, cmap=popmap.cmap, vmin=popmap.vmin, vmax=popmap.vmax, zorder=POP_ZORDER, interpolation='nearest') # draw 10m res coastlines ax.coastlines(resolution="10m", zorder=COAST_ZORDER); states_provinces = cfeature.NaturalEarthFeature( category='cultural', name='admin_1_states_provinces_lines', scale='50m', facecolor='none') ax.add_feature(states_provinces, edgecolor='black',zorder=COAST_ZORDER) # draw country borders using natural earth data set if borderfile is not None: borders = ShapelyFeature(Reader(borderfile).geometries(), ccrs.PlateCarree()) ax.add_feature(borders, zorder=COAST_ZORDER, edgecolor='black', linewidth=2, facecolor='none') # clip the ocean data to the shakemap bbox = (gd.xmin, gd.ymin, gd.xmax, gd.ymax) oceanshapes = _clip_bounds(bbox, oceanfile) ax.add_feature(ShapelyFeature(oceanshapes, crs=geoproj), facecolor=WATERCOLOR, zorder=OCEAN_ZORDER) # It turns out that when presented with a map that crosses the 180 meridian, # the matplotlib/cartopy contouring routine thinks that the 180 meridian is a map boundary # and only plots one side of the contour. Contouring the geographic MMI data and then # projecting the resulting contour vectors does the trick. Sigh. # define contour grid spacing contoury = np.linspace(ymin, ymax, gd.ny) contourx = np.linspace(xmin, xmax, gd.nx) # smooth the MMI data for contouring mmi = shakegrid.getLayer('mmi').getData() smoothed_mmi = gaussian_filter(mmi, FILTER_SMOOTH) # create masked arrays of the ocean grid landmask = np.ma.masked_where(oceangrid._data == 0.0, smoothed_mmi) oceanmask = np.ma.masked_where(oceangrid._data == 1.0, smoothed_mmi) # contour the data land_contour = plt.contour(contourx, contoury, np.flipud(oceanmask), linewidths=3.0, linestyles='solid', zorder=LANDC_ZORDER, cmap=mmimap.cmap, vmin=mmimap.vmin, vmax=mmimap.vmax, levels=np.arange(0.5, 10.5, 1.0), transform=geoproj) ocean_contour = plt.contour(contourx, contoury, np.flipud(landmask), linewidths=2.0, linestyles='dashed', zorder=OCEANC_ZORDER, cmap=mmimap.cmap, vmin=mmimap.vmin, vmax=mmimap.vmax, levels=np.arange(0.5, 10.5, 1.0), transform=geoproj) # the idea here is to plot invisible MMI contours at integer levels and then label them. # clabel method won't allow text to appear, which is this case is kind of ok, because # it allows us an easy way to draw MMI labels as roman numerals. cs_land = plt.contour(contourx, contoury, np.flipud(oceanmask), linewidths=0.0, levels=np.arange(0, 11),alpha=0.0, zorder=CLABEL_ZORDER, transform=geoproj) clabel_text = ax.clabel(cs_land, np.arange(0, 11), colors='k', zorder=CLABEL_ZORDER, fmt='%.0f', fontsize=40) for clabel in clabel_text: x, y = clabel.get_position() label_str = clabel.get_text() roman_label = MMI_LABELS[label_str] th=plt.text(x, y, roman_label, zorder=CLABEL_ZORDER, ha='center', va='center', color='black', weight='normal', size=16) th.set_path_effects([path_effects.Stroke(linewidth=2.0, foreground='white'), path_effects.Normal()]) cs_ocean = plt.contour(contourx, contoury, np.flipud(landmask), linewidths=0.0, levels=np.arange(0, 11), zorder=CLABEL_ZORDER, transform=geoproj) clabel_text = ax.clabel(cs_ocean, np.arange(0, 11), colors='k', zorder=CLABEL_ZORDER, fmt='%.0f', fontsize=40) for clabel in clabel_text: x, y = clabel.get_position() label_str = clabel.get_text() roman_label = MMI_LABELS[label_str] th=plt.text(x, y, roman_label, zorder=CLABEL_ZORDER, ha='center', va='center', color='black', weight='normal', size=16) th.set_path_effects([path_effects.Stroke(linewidth=2.0, foreground='white'), path_effects.Normal()]) # draw meridians and parallels using Cartopy's functions for that gl = ax.gridlines(draw_labels=True, linewidth=2, color=(0.9, 0.9, 0.9), alpha=0.5, linestyle='-', zorder=GRID_ZORDER) gl.xlabels_top = False gl.xlabels_bottom = False gl.ylabels_left = False gl.ylabels_right = False gl.xlines = True step = 1 # let's floor/ceil the edges to nearest half a degree gxmin = np.floor(xmin * 2) / 2 gxmax = np.ceil(xmax * 2) / 2 gymin = np.floor(ymin * 2) / 2 gymax = np.ceil(ymax * 2) / 2 xlocs = np.linspace(gxmin, gxmax+0.5, num=5) ylocs = np.linspace(gymin, gymax+0.5, num=5) gl.xlocator = mticker.FixedLocator(xlocs) gl.ylocator = mticker.FixedLocator(ylocs) gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER gl.xlabel_style = {'size': 15, 'color': 'black'} gl.ylabel_style = {'size': 15, 'color': 'black'} # TODO - figure out x/y axes data coordinates corresponding to 10% from left # and 10% from top # use geoproj and proj dleft = 0.01 dtop = 0.97 proj_str = proj.proj4_init merc_to_dd = pyproj.Proj(proj_str) # use built-in transforms to get from axes units to data units display_to_data = ax.transData.inverted() axes_to_display = ax.transAxes # these are x,y coordinates in projected space yleft, t1 = display_to_data.transform(axes_to_display.transform((dleft, 0.5))) t2, xtop = display_to_data.transform(axes_to_display.transform((0.5, dtop))) # these are coordinates in lon,lat space yleft_dd, t1_dd = merc_to_dd(yleft, t1, inverse=True) t2_dd, xtop_dd = merc_to_dd(t2, xtop, inverse=True) # drawing our own tick labels INSIDE the plot, as Cartopy doesn't seem to support this. yrange = ymax - ymin xrange = xmax - xmin ddlabelsize = 12 for xloc in gl.xlocator.locs: outside = xloc < xmin or xloc > xmax # don't draw labels when we're too close to either edge near_edge = (xloc-xmin) < (xrange*0.1) or (xmax-xloc) < (xrange*0.1) if outside or near_edge: continue xtext = r'$%.1f^\circ$W' % (abs(xloc)) ax.text(xloc, xtop_dd, xtext, fontsize=ddlabelsize, zorder=GRID_ZORDER, ha='center', fontname=DEFAULT_FONT, transform=ccrs.Geodetic()) for yloc in gl.ylocator.locs: outside = yloc < gd.ymin or yloc > gd.ymax # don't draw labels when we're too close to either edge near_edge = (yloc-gd.ymin) < (yrange*0.1) or (gd.ymax-yloc) < (yrange*0.1) if outside or near_edge: continue if yloc < 0: ytext = r'$%.1f^\circ$S' % (abs(yloc)) else: ytext = r'$%.1f^\circ$N' % (abs(yloc)) thing = ax.text(yleft_dd, yloc, ytext, fontsize=ddlabelsize, zorder=GRID_ZORDER, va='center', fontname=DEFAULT_FONT, transform=ccrs.Geodetic()) # draw cities mapcities = mmap.drawCities(shadow=True, zorder=CITIES_ZORDER) # draw the figure border thickly # TODO - figure out how to draw map border # bwidth = 3 # ax.spines['top'].set_visible(True) # ax.spines['left'].set_visible(True) # ax.spines['bottom'].set_visible(True) # ax.spines['right'].set_visible(True) # ax.spines['top'].set_linewidth(bwidth) # ax.spines['right'].set_linewidth(bwidth) # ax.spines['bottom'].set_linewidth(bwidth) # ax.spines['left'].set_linewidth(bwidth) # Get the corner of the map with the lowest population corner_rect, filled_corner = _get_open_corner(popgrid, ax) clat2 = round_to_nearest(center_lat, 1.0) clon2 = round_to_nearest(center_lon, 1.0) # draw a little globe in the corner showing in small-scale where the earthquake is located. # proj = ccrs.Orthographic(central_latitude=clat2, # central_longitude=clon2) # ax2 = fig.add_axes(corner_rect,projection=proj) # ax2.add_feature(cartopy.feature.OCEAN, zorder=0,facecolor=WATERCOLOR,edgecolor=WATERCOLOR) # ax2.add_feature(cartopy.feature.LAND, zorder=0, edgecolor='black') # ax2.plot([clon2],[clat2],'w*',linewidth=1,markersize=16,markeredgecolor='k',markerfacecolor='r') # gh=ax2.gridlines(); # ax2.set_global(); # ax2.outline_patch.set_edgecolor('black') # ax2.outline_patch.set_linewidth(2); # Draw the map scale in the unoccupied lower corner. corner = 'lr' if filled_corner == 'lr': corner = 'll' draw_scale(ax, corner, pady=0.05, padx=0.05) # Draw the epicenter as a black star plt.sca(ax) plt.plot(center_lon, center_lat, 'k*', markersize=16, zorder=EPICENTER_ZORDER, transform=geoproj) if is_scenario: plt.text(center_lon, center_lat, 'SCENARIO', fontsize=64, zorder=WATERMARK_ZORDER, transform=geoproj, alpha=0.2, color='red', horizontalalignment='center') # create pdf and png output file names pdf_file = basename+'.pdf' png_file = basename+'.png' # save to pdf plt.savefig(pdf_file) plt.savefig(png_file) return (pdf_file, png_file, mapcities)
xticks = range(72, 137, 5) yticks = range(15, 55, 5) ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True) ax.add_geometries([extent_box], ccrs.PlateCarree(), color='white', alpha=0.5, edgecolor='black', linewidth=2) fname = Path(datapath, 'bou1_4l.shp') f2name = Path(datapath, 'bou2_4l.shp') faults = Path(datapath, 'gem_active_faults.shp') ax.add_geometries(Reader(str(faults)).geometries(), ccrs.PlateCarree(), facecolor='none', edgecolor='red') ax.add_geometries(Reader(str(f2name)).geometries(), ccrs.PlateCarree(), facecolor='none', edgecolor='gray', linestyle=':') ax.add_geometries(Reader(str(fname)).geometries(), ccrs.PlateCarree(), facecolor='none', edgecolor='black')
#set up data for plotting via levels vmax=pd.DataFrame(data).max().max() vmin= int(pd.DataFrame(data).min().min()) vmax=-.5 vmin=-1.5 levels = np.linspace(vmin, int(vmax), 15) # get rid of values outside the levels we are contouring to data[pd.DataFrame(data)<vmin]=vmin # set boundary as outer extent by making a matplotlib path object and adding that geometry # i think setting the boundary before you plot the data actually crops the data to the shape, so set ax first axs.set_boundary(mpath.Path(outsideofunion.T,closed=True), transform= crs_new, use_as_clip_path=True) axs.add_geometries(Reader(path).geometries(), crs=crs_new,facecolor='None', edgecolor='black') #plot the gridded data by using contourf cs=plt.contourf(lon,lat,data,cmap= "inferno", transform=crs_new, levels=levels) # add landmarks with scatterplot midway= 41.7868, -87.7522 ohare = 41.9742, -87.9073 loop = 41.8786, -87.6251 #plt.scatter(pd.DataFrame([midway,ohare,loop])[1],pd.DataFrame([midway,ohare,loop])[0],marker = '*',color='white') # set axes extents from shapefile x=[min(chi.bounds.minx), max(chi.bounds.maxx)] y=[min(chi.bounds.miny), max(chi.bounds.maxy)] axs.set_extent([x[0]-.03,x[1]+.03,y[0]-.03,y[1]+.03],crs= crs_new) axs.set_title('1 PM Change in Emissions from Scenario 2')
reload(geo_plots) import matplotlib.pyplot as plt import datetime from cartopy.io.shapereader import Reader import os import numpy as np plt.clf() ax = geo_plots.setup_3d(bbox=(-88, -87, 27.5, 28.5, 0, 2000)) # if bbox not specified, this will use map bounds from bna # add bathymetry bathy_file = os.path.join('gom_bathy', 'Bathymetry.shp') bathy = Reader(bathy_file) for rec, geo in zip(bathy.records(), bathy.geometries()): if rec.attributes['DEPTH_METR'] in ['1000m']: print rec.attributes['DEPTH_METR'] for g in geo: x = g.xy[0] y = g.xy[1] ax.plot3D(x, y, 1000 * np.ones_like(x), 'k') ax.set_xlim(-87.5, -86.9) ax.set_ylim(27.6, 28.7) # add particles at one time t0 = datetime.datetime(2016, 9, 18, 1) # ax = geo_plots.plot_particles(ax,'script_plume.nc',t0,color='b')
import numpy as np import cartopy.feature as cpf import cartopy.crs as ccrs import matplotlib.pyplot as plt import cartopy.io.img_tiles as cimgt import pandas as pd from cartopy.io.shapereader import Reader from cartopy.feature import ShapelyFeature extent = [-109.069, -105.6, 38.85, 40.50] extent_large = [-111.0, -101.0, 36.5, 41.5] #rivers_10m = cpf.NaturalEarthFeature('physical', 'rivers_lake_centerlines', '10m') #tiles = cimgt.StamenTerrain() shape_feature = ShapelyFeature(Reader( '../../Structures_files/Shapefiles/Water_Districts.shp').geometries(), ccrs.PlateCarree(), edgecolor='black', facecolor='None') flow_feature = ShapelyFeature( Reader('../../Structures_files/Shapefiles/UCRBstreams.shp').geometries(), ccrs.PlateCarree(), edgecolor='royalblue', facecolor='None') months = 12 years = 105 param_names = [ 'IWRmultiplier', 'RESloss', 'TBDmultiplier', 'M_Imultiplier', 'ShoshoneDMND', 'ENVflows', 'EVAdelta', 'XBM_mu0', 'XBM_sigma0', 'XBM_mu1', 'XBM_sigma1', 'XBM_p00', 'XBM_p11', 'shift', 'Interactions', 'N/A' ]
del(src_tf_arr) amsr2_1km_mean_1 = np.nanmean(amsr2_1km_agg_stack[:, :, :days_n], axis=2) amsr2_1km_mean_2 = np.nanmean(amsr2_1km_agg_stack[:, :, days_n:], axis=2) amsr2_1km_mean_1_all[imo, :, :] = amsr2_1km_mean_1 amsr2_1km_mean_2_all[imo, :, :] = amsr2_1km_mean_2 del(amsr2_1km_mean_1, amsr2_1km_mean_2) amsr2_data_stack = np.stack((amsr2_1km_mean_1_all, amsr2_9km_mean_1_all, amsr2_1km_mean_2_all, amsr2_9km_mean_2_all)) # 1.2 Maps of April, 2019 xx_wrd, yy_wrd = np.meshgrid(lon_world_ease_9km, lat_world_ease_9km) # Create the map matrix shape_world = ShapelyFeature(Reader(path_gis_data + '/gshhg-shp-2.3.7/GSHHS_shp/c/GSHHS_c_L1.shp').geometries(), ccrs.PlateCarree(), edgecolor='black', facecolor='none') title_content = ['1 km (04/01 - 04/08)', '10 km (04/01 - 04/08)', '1 km (04/09 - 04/16)', '10 km (04/09 - 04/16)'] columns = 2 rows = 2 fig = plt.figure(figsize=(13, 8), facecolor='w', edgecolor='k') for ipt in range(len(monthname)//3): ax = fig.add_subplot(rows, columns, ipt+1, projection=ccrs.PlateCarree(), extent=[-180, 180, -70, 90]) ax.add_feature(shape_world, linewidth=0.5) img = ax.pcolormesh(xx_wrd, yy_wrd, amsr2_data_stack[ipt, 0, :, :], vmin=0, vmax=0.5, cmap='gist_earth_r') gl = ax.gridlines(draw_labels=True, linestyle='--', linewidth=0.5, alpha=0.5, color='black') gl.xlocator = mticker.FixedLocator([-180, -90, 0, 90, 180]) gl.ylocator = mticker.FixedLocator([90, 45, 0, -45, -90]) gl.xlabel_style = {'size': 13}
timeOfValidity = ds.attrs['timeOfValidity'] lon0 = 119 lon1 = 128.5 lat0 = 29 lat1 = 36 colors = np.array( [ [255,255,255],[166,242,143], [61,186,61], [97,184,255], [0,0,225], \ [250,0,250], [128,0,64]] ,dtype='f4') cmap = matplotlib.colors.ListedColormap(colors / 255., name='rain_cmap') levels = np.array([0.1, 10, 25, 50, 100, 250], dtype='f4') cnfont = {'fontname': 'simhei'} plt.figure(figsize=(11, 11), dpi=100) ax = plt.axes(projection=ccrs.PlateCarree()) ax.add_geometries(Reader(subfname).geometries(), ccrs.PlateCarree(), facecolor='none', edgecolor='black', linewidth=1, alpha=0.6) ax.coastlines('10m', linewidth=1.9) land = cfeature.NaturalEarthFeature('physical', 'land', '10m', edgecolor='face', facecolor=cfeature.COLORS['land']) ax.add_feature(land, facecolor='0.85') im = ds.r24h.plot.contourf(ax=ax, xlim=(lon0, lon1),
map2 = ax[0,1].contourf(dset['lon'], dset['lat'], season[2,:,:], cmap='BuPu', levels=np.arange(50, 500, 50), extend='both') map3 = ax[1,0].contourf(dset['lon'], dset['lat'], season[1,:,:], cmap='BuPu', levels=np.arange(50, 500, 50), extend='both') map4 = ax[1,1].contourf(dset['lon'], dset['lat'], season[3,:,:], cmap='BuPu', levels=np.arange(50, 500, 50), extend='both') ax[1,0].colorbar(map3, loc='b', label='mm/month', shrink=0.1) ax[1,1].colorbar(map4, loc='b', label='mm/month', shrink=0.1) ax[0,0].format(title='DJF') ax[0,1].format(title='MAM') ax[1,0].format(title='JJA') ax[1,1].format(title='SON') ax[0,0].add_geometries(Reader(basin).geometries(), proj, edgecolor='black', facecolor='none') ax[0,1].add_geometries(Reader(basin).geometries(), proj, edgecolor='black', facecolor='none') ax[1,0].add_geometries(Reader(basin).geometries(), proj, edgecolor='black', facecolor='none') ax[1,1].add_geometries(Reader(basin).geometries(), proj, edgecolor='black', facecolor='none') f.save('rainfall_seasonality.jpeg') plt.show() # Fig. 3 ''' This is the Standardized Precipitation-Evaporation Index (SPEI) from the Global SPEI database. Link: https://spei.csic.es/home.html '''
# + import matplotlib.pyplot as plt # %matplotlib inline import cartopy.crs as ccrs from cartopy.io.shapereader import Reader from cartopy.feature import ShapelyFeature ax = plt.axes(projection=ccrs.LambertConformal( central_latitude=39, central_longitude=-96, standard_parallels=(33, 45))) ax.set_extent([-125, -66.5, 20, 50]) # Read in county-level shapefiles fname = "/data301/data/cb_2017_us_county_5m/cb_2017_us_county_5m" shp = Reader(fname) # Add each county to the data set. ax.add_geometries(shp.geometries(), ccrs.PlateCarree(), facecolor="None", edgecolor='black') # - # To make a choropleth, we simply need to set the `facecolor` of each geometry. First, let's read in some county-level data that we can plot. import pandas as pd election_df = pd.read_csv( "https://raw.githubusercontent.com/dlsun/data-science-book/" "master/data/election2016.csv") election_df
def cartoplot_bay_price_predictions(data, mapsize, pricequintiles, shapefile): # Create a Stamen terrain background instance stamen_terrain = cimgt.Stamen('terrain-background') fig = plt.figure(figsize=(mapsize, mapsize)) ax = fig.add_subplot(1, 1, 1, projection=stamen_terrain.crs) # Set range of map, stipulate zoom level ax.set_extent([-122.7, -121.5, 37.15, 38.15], crs=ccrs.Geodetic()) ax.add_image(stamen_terrain, 12, zorder=0) # Add city borders shape_feature = ShapelyFeature(Reader(shapefile).geometries(), ccrs.epsg(26910), linewidth=2, facecolor=(1, 1, 1, 0), edgecolor=(0.3, 0.3, 0.3, 1)) ax.add_feature(shape_feature, zorder=1) # Determine plotting mode and subdivide data based on quintiles q1 = data.loc[data['Price difference'] < pricequintiles[0]] q2 = data.loc[(data['Price difference'] > pricequintiles[0]) & (data['Price difference'] < pricequintiles[1])] q3 = data.loc[(data['Price difference'] > pricequintiles[1]) & (data['Price difference'] < pricequintiles[2])] q4 = data.loc[(data['Price difference'] > pricequintiles[2]) & (data['Price difference'] < pricequintiles[3])] q5 = data.loc[data['Price difference'] > pricequintiles[3]] # Create legend labels l1 = '< -$%s K' % str(int(round(-pricequintiles[0] / 1000, 3))) l2 = '-\$%s K to -$%s K' % (int(round(-pricequintiles[0] / 1000, 2)), int(round(-pricequintiles[1] / 1000, 3))) l3 = '-\$%s K to $%s K' % (int(round(-pricequintiles[1] / 1000, 3)), int(round(pricequintiles[2] / 1000, 3))) l4 = '\$%s K to $%s K' % (int(round( pricequintiles[2] / 1000, 3)), int(round(pricequintiles[3] / 1000, 3))) l5 = '> $%s K' % str(int(round(pricequintiles[3] / 1000, 3))) # Plot scatter based on price quintiles ax.scatter(q1['Longitude'], q1['Latitude'], s=55, zorder=2, c='darkred', edgecolors='black', transform=ccrs.PlateCarree(), label=l1) ax.scatter(q2['Longitude'], q2['Latitude'], s=55, zorder=2, c='salmon', edgecolors='black', transform=ccrs.PlateCarree(), label=l2) ax.scatter(q3['Longitude'], q3['Latitude'], s=55, zorder=2, c='grey', edgecolors='black', transform=ccrs.PlateCarree(), label=l3) ax.scatter(q4['Longitude'], q4['Latitude'], s=55, zorder=2, c='cornflowerblue', edgecolors='black', transform=ccrs.PlateCarree(), label=l4) ax.scatter(q5['Longitude'], q5['Latitude'], s=55, zorder=2, c='darkblue', edgecolors='black', transform=ccrs.PlateCarree(), label=l5) # Add text box to map lgnd = ax.legend(loc=3, prop={ 'family': 'Helvetica', 'size': 30 }, title=r'$\bf{Actual\/-\/predicted\/price}$', title_fontsize=33) #change the marker size manually for both lines lgnd.legendHandles[0]._sizes = [150] lgnd.legendHandles[1]._sizes = [150] lgnd.legendHandles[2]._sizes = [150] lgnd.legendHandles[3]._sizes = [150] lgnd.legendHandles[4]._sizes = [150] plt.show()
start_time = datetime.datetime.utcnow() fname = r'./GADM/gadm36_USA_2.shp' # For determining land boundaries geoms = fiona.open(fname) land_geom = sgeom.MultiPolygon([sgeom.shape(geom['geometry']) for geom in geoms]) land = prep(land_geom) grid = generate_grid() # Plot setup fig = plt.figure() request = cimgt.GoogleTiles() ax = plt.axes(projection=ccrs.PlateCarree()) shape_feature = ShapelyFeature(Reader(fname).geometries(), ccrs.PlateCarree(), edgecolor='black') ax.add_feature(shape_feature, alpha=1) extent = generate_extent() ax.set_extent(extent) ax.add_image(request, 10, interpolation='bilinear', zorder=2) cmap = colors.ListedColormap([(0,0,0,0), 'green', 'yellow', 'orange', 'red']) bounds = [0, .25, .5, .75, .9, 1] norm = colors.BoundaryNorm(bounds, cmap.N) pdf = plt.imshow(np.zeros((21,21)), cmap=cmap, extent=extent, alpha=0.5, zorder=10) ani = animation.FuncAnimation(fig, plot_search, frames=search, blit=False, repeat=False) cid = fig.canvas.mpl_connect('button_press_event', onclick) #mng = plt.get_current_fig_manager() #mng.full_screen_toggle()
DIFF[[1, 2, 3]].mean(dim='month').values, transform=ccrs.PlateCarree(), levels=levs, cmap='BrBG', extend='both') ax1.set_extent([ext_e, ext_w, ext_s, ext_n]) states_provinces = cfeature.NaturalEarthFeature( category='cultural', name='admin_1_states_provinces_lines', scale='50m', facecolor='none') ax1.add_feature(states_provinces, edgecolor='black', linewidth=0.2) ax1.add_feature(cfeature.COASTLINE) ax1.add_feature(cfeature.BORDERS) shape_feature = ShapelyFeature(Reader( '/Users/gbromley/Dropbox/Montana_Climate_Project/Study_Area/NGP_Study_Area/Study_Area_08_01_17.shp' ).geometries(), crs=ccrs.PlateCarree(), facecolor='none', edgecolor='black') ax1.add_feature(shape_feature) ax1.title.set_text('DJF') at = AnchoredText( "a", prop=dict(size=8), frameon=True, loc=2, #backgroundcolor = 'lightgray' ) ax1.add_artist(at)
import matplotlib.pyplot as plt import cartopy.crs as ccrs from cartopy.io.shapereader import Reader from cartopy.feature import ShapelyFeature fname = 'F:\\jupyter\\shapefiles\\st_mx.shp' ax = plt.axes(projection=ccrs.Robinson()) shape_feature = ShapelyFeature(Reader(fname).geometries(), ccrs.PlateCarree(), facecolor='none', edgecolor='black') ax.set_extent((-105, -95, 16, 22)) ax.add_feature(shape_feature) plt.show()
nas_son = np.logical_or(np.isnan(gc_data_nitrate_son), np.isnan(sites_nitrate_son_c)) correlate_son = stats.pearsonr(gc_data_nitrate_son[~nas_son], sites_nitrate_son_c[~nas_son]) nas_djf = np.logical_or(np.isnan(gc_data_nitrate_djf), np.isnan(sites_nitrate_djf_c)) correlate_djf = stats.pearsonr(gc_data_nitrate_djf[~nas_djf], sites_nitrate_djf_c[~nas_djf]) print('Correlation = ', correlate_Annual) # plotting spatial map model and DEFRA network os.chdir('/home/a/ap744/scratch_alok/shapefiles/GBP_shapefile') Europe_shape = r'GBR_adm1.shp' Europe_map = ShapelyFeature(Reader(Europe_shape).geometries(), ccrs.PlateCarree(), edgecolor='black', facecolor='none') print('Shapefile_read') title_list = 'DEFRA and GEOS-Chem Particulate nitrate' title_list1 = 'Spatial Map DEFRA and GEOS-Chem Particulate nitrate' #fig,ax = plt.subplots(2,1, figsize=(11,11)) fig1 = plt.figure(facecolor='White', figsize=[11, 11]) pad = 1.1 # plt.suptitle(title_list, fontsize = 35, y=0.96) ax = plt.subplot(231) #plt.title(title_list1, fontsize = 30, y=1) ax = plt.axes(projection=ccrs.PlateCarree())
for j in range(len(model_columns[0])): #for i in range(1): # for j in range(1): data = model_columns[i][j][0] * 10**-15 fig, ax = plt.subplots(subplot_kw={'projection': crs_new}, figsize=(10, 6)) #ax.set_boundary(mpath.Path(outsideofunion.T,closed=True), transform= crs_new, use_as_clip_path=True) cs = ax.pcolormesh(lon, lat, data, transform=crs_new, cmap=cmap, vmin=vmin, vmax=vmax) cbar = plt.colorbar(cs, boundaries=levels, shrink=0.5) cbar.set_ticks(levels) ax.add_geometries(Reader(path).geometries(), crs=crs_new, facecolor='None', edgecolor='black') x = [chi_shapefile.bounds.minx.min(), chi_shapefile.bounds.maxx.max()] y = [chi_shapefile.bounds.miny.min(), chi_shapefile.bounds.maxy.max()] #ax.set_extent([x[0]-.03,x[1]+.03,y[0]-.03,y[1]+.03],crs= crs_new) ax.set_extent([xl, xu, yl, yu], crs=crs_new) ax.set_title('CMAQ Column') states = cfeature.STATES.with_scale('10m') ax.add_feature(states) plt.savefig(fig_dir + 'timeseries_model_column_d' + str(i) + '_h' + str(j) + '.png') plt.close()