def from_shapefile(cls, shapefile, *args, **kwargs): """ Loads a shapefile from disk and optionally merges it with a dataset. See ``from_records`` for full signature. Parameters ---------- records: list of cartopy.io.shapereader.Record Iterator containing Records. dataset: holoviews.Dataset Any HoloViews Dataset type. on: str or list or dict A mapping between the attribute names in the records and the dimensions in the dataset. value: str The value dimension in the dataset the values will be drawn from. index: str or list One or more dimensions in the dataset the Shapes will be indexed by. drop_missing: boolean Whether to drop shapes which are missing from the provides dataset. Returns ------- shapes: Polygons or Path object A Polygons or Path object containing the geometries """ reader = Reader(shapefile) return cls.from_records(reader.records(), *args, **kwargs)
def from_shapefile(cls, shapefile, *args, **kwargs): """ Loads a shapefile from disk and optionally merges it with a dataset. See ``from_records`` for full signature. """ reader = Reader(shapefile) return cls.from_records(reader.records(), *args, **kwargs)
def distribution_geoaxes(): from cartopy.mpl.geoaxes import GeoAxes from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter from mpl_toolkits.axes_grid1 import AxesGrid projection = ccrs.PlateCarree() axes_class = (GeoAxes, dict(map_projection=projection)) fig = plt.figure(figsize=(16, 9)) axgr = AxesGrid(fig, 111, axes_class=axes_class, nrows_ncols=(2, 2), axes_pad=0.2, cbar_location='right', cbar_mode='single', cbar_pad=0.2, cbar_size='2%', label_mode='') # note the empty label_mode doc_fp = r'I:\Qinghai_Tibet_Plateau\GlcAnysis\SiteData\观测数据\GlcDOC\GlcDOC.shp' doc_data = gpd.read_file(doc_fp) sample_type_list = ['snow', 'snow_pit', 'ice', 'ice_core'] for i, ax in enumerate(axgr): print(sample_type_list[i]) sample_type = sample_type_list[i] data_type = doc_data[doc_data.Type==sample_type_list[i]] lons, lats = data_type.CorrPt_x, data_type.CorrPt_y # Tibetan plateau # tp_fp = r'I:\Qinghai_Tibet_Plateau\GlcAnysis\Shapefile\TP_counties\TP_counties.shp' tp_fp = r'I:\Qinghai_Tibet_Plateau\青藏高原范围与界线数据\DBATP\DBATP\DBATP_Polygon.shp' tp_counties_fp = r'I:\Qinghai_Tibet_Plateau\GlcAnysis\Shapefile\TP_counties\TP_counties_wgs84.shp' tp_shape_feature = ShapelyFeature(Reader(tp_fp).geometries(), ccrs.PlateCarree(), facecolor="#F6F7FC") # facecolor='#F6F7FC' tp_counties_shape_feature = ShapelyFeature(Reader(tp_counties_fp).geometries(), ccrs.PlateCarree(), facecolor="#F6F7FC") ax.add_feature(cfeature.LAND, facecolor='#E7E2DF',zorder=1) ax.add_feature(cfeature.OCEAN, zorder=2) ax.add_feature(cfeature.COASTLINE, zorder=3) # ax.add_feature(cfeature.BORDERS, linestyle='-') ax.add_feature(cfeature.LAKES, alpha=0.5, zorder=4) # ax.add_feature(cfeature.RIVERS, zorder=5) ax.set_extent([73, 105, 40, 25.5], crs=ccrs.PlateCarree()) # ax.set_xticks(np.linspace(-180, 180, 5), crs=projection) # ax.set_yticks(np.linspace(-90, 90, 5), crs=projection) lon_formatter = LongitudeFormatter(zero_direction_label=True) lat_formatter = LatitudeFormatter() ax.xaxis.set_major_formatter(lon_formatter) ax.yaxis.set_major_formatter(lat_formatter) ax.add_feature(tp_shape_feature, edgecolor='gray', zorder=6) ax.add_feature(tp_counties_shape_feature, edgecolor='gray', zorder=6.5) cmap = mpl.cm.rainbow s = ax.scatter(lons, lats, c=data_type.DOC, cmap=cmap, vmin=0.15, vmax=2.7, transform=ccrs.PlateCarree(), zorder=7) ax.annotate(sample_type_dict[sample_type], xy=(10, 10), xycoords='axes points', fontsize=14, zorder=8) axgr.cbar_axes[0].colorbar(s) # fig.colorbar(s, shrink=0.6, location='right', extend='both') plt.show()
def doc_distribution(): fig = plt.figure(figsize=(12.8, 5.4), constrained_layout=True) # subfigs = fig.subfigures(1, 2, wspace=0.07) # doc_fp = r'I:\Qinghai_Tibet_Plateau\GlcAnysis\SiteData\观测数据\GlcDOC\GlcDOC.shp' doc_fp = r'I:\Data\DOC\Shapefile\GlcDOCMean\GlcDOCMean.shp' doc_data = gpd.read_file(doc_fp) sample_type_list = ['sonw', 'snow_pit', 'ice', 'ice_core'] sample_type_dict = { 'snow' : "Snow", 'snow_pit': 'Snow Pit', 'ice' : 'Ice', 'ice_core': 'Ice Core' } axes = [] for index, sample_type in enumerate(sample_type_dict.keys()): ax = fig.add_subplot(2, 2, index+1, projection=ccrs.PlateCarree()) axes.append(ax) ax.set_extent([73, 105, 40, 25.5], crs=ccrs.PlateCarree()) # Tibetan plateau # tp_fp = r'I:\Qinghai_Tibet_Plateau\GlcAnysis\Shapefile\TP_counties\TP_counties.shp' tp_fp = r'I:\Qinghai_Tibet_Plateau\青藏高原范围与界线数据\DBATP\DBATP\DBATP_Polygon.shp' line_32 = r'I:\Qinghai_Tibet_Plateau\GlcAnysis\Shapefile\32N\32N.shp' tp_counties_fp = r'I:\Qinghai_Tibet_Plateau\GlcAnysis\Shapefile\TP_counties\TP_counties_wgs84.shp' tp_shape_feature = ShapelyFeature(Reader(tp_fp).geometries(), ccrs.PlateCarree(), facecolor="#F6F7FC") # facecolor='#F6F7FC' tp_counties_shape_feature = ShapelyFeature(Reader(tp_counties_fp).geometries(), ccrs.PlateCarree(), facecolor="#F6F7FC") line_32_feature = ShapelyFeature(Reader(line_32).geometries(), ccrs.PlateCarree(), facecolor="#F6F7FC") ax.add_feature(cfeature.LAND, facecolor='#E7E2DF', zorder=1) ax.add_feature(cfeature.OCEAN, zorder=2) ax.add_feature(cfeature.COASTLINE, zorder=3) # ax.add_feature(cfeature.BORDERS, linestyle='-') ax.add_feature(cfeature.LAKES, alpha=0.5, zorder=4) # ax.add_feature(cfeature.RIVERS, zorder=5) # ax.add_feature(states_provinces, edgecolor='gray') ax.add_feature(tp_shape_feature, edgecolor='gray', zorder=6) # ax.add_feature(tp_counties_shape_feature, edgecolor='gray', zorder=6.5) ax.add_feature(line_32_feature, edgecolor='black', linestyle='--', alpha=0.5, zorder=7) data_type = doc_data[doc_data.Type==sample_type] lons, lats = data_type.Lon, data_type.Lat cmap = mpl.cm.rainbow s = ax.scatter(lons, lats, c=data_type['DOC_mg_L_'], s=50, cmap=cmap, vmin=0.15, vmax=2.7, transform=ccrs.PlateCarree(), zorder=7) # ax.annotate(sample_type_dict[sample_type], xy=(10, 10), xycoords='axes points', # fontsize=14, # zorder=8) text = AnchoredText(sample_type_dict[sample_type], loc=3, prop={'size': 12}, frameon=True) ax.add_artist(text) ax.annotate("32°N", xy=(10, 88), xycoords='axes points', fontsize=14, zorder=8) # fig.tight_layout(pad=1, w_pad=0.29, h_pad=0.64) # plt.subplots_adjust(wspace=0.01, hspace=0.5) # 调整子图间距 # norm = mpl.colors.Normalize(vmin=0.15, vmax=2.7) fig.colorbar(s, ax=axes, location='right', shrink=0.5, extend='both', pad=0.01) # plt.colorbar(cax=data_type) plt.show() return
def shelf(self): """returns Mueller ice shelf as :class:`shapely.geometry.Polygon` based on :attr:`coastline_file`""" R = Reader(os.path.join(self.path, self.coastline_file)) recs = [r for r in R.records() if r.attributes['FID_Coastl'] in self.shelf_features] # order is important geoms = [[r.geometry for r in recs if r.attributes['FID_Coastl']==f][0] for f in self.shelf_features] pts = np.hstack([np.r_['1,2', p.xy] for g in geoms for p in g.geoms]).T.tolist() # important! planar geometry ('False') # https://developers.google.com/earth-engine/geometries_planar_geodesic return ee.Geometry.Polygon(pts, 'EPSG:{}'.format(self.quanta_epsg), False)
def plot_basic_cappi(path, filename, level, shape_rivers, shape_states): """ """ radar = read_sipam_cappi(filename) date = pyart.util.datetime_from_grid(radar) str_level = str(radar.z["data"][level] / 1000) fig = plt.figure(figsize=(8, 7)) ax = fig.add_subplot(111, projection=ccrs.PlateCarree()) display = pyart.graph.GridMapDisplay(radar) display.plot_grid("DBZc", level=level, vmin=0, vmax=70, ax=ax, cmap="dbz", embelish=False) ax.add_geometries( Reader(path + shape_rivers).geometries(), ccrs.PlateCarree(), linewidth=0.75, facecolor="None", edgecolor="darkblue", alpha=0.3, ) ax.add_geometries( Reader(path + shape_states).geometries(), ccrs.PlateCarree(), linewidth=0.75, facecolor="None", edgecolor="darkgray", alpha=0.8, ) gl = ax.gridlines( crs=ccrs.PlateCarree(), draw_labels=True, xlocs=np.arange(-70, -50, 1), ylocs=np.arange(-10, 1, 1), ) gl.top_labels = gl.right_labels = False gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER plt.savefig( path + "radar_processing/figs/sipam_cappi/sipam_" + str_level + "_dBZ_" + date.strftime("%Y%m%d%H%M%S") + ".png", bbox_inches="tight", dpi=300, facecolor="None", edgecolor="white", ) plt.close() print("Plotted! " + str(date) + " - " + str_level + " km")
def obtain_map_info(self, path): """ Return the records (record = (attributes, geometry)) of the shapefile Parameters : - path = path of the shapefile to read CountryMap(*args).obtain_map_info() ==> record :->generator""" self.path_shp_commune = path reader = Reader(path) records = reader.records() return records
def make_african_land(): from cartopy.io.shapereader import Reader, natural_earth from shapely.ops import unary_union shpfile = Reader(natural_earth(resolution='110m', category='cultural', name='admin_0_countries')) filtered_records = shpfile.records() filtered_records = filter(lambda x: x.attributes['continent'] == 'Africa', filtered_records) region_poly = unary_union([r.geometry for r in filtered_records]) return region_poly
def plot(h): msg_folder = cnst.GRIDSAT_PERU htag1 = str(h).zfill(2) + 'UTC_2010-2017' p1 = 'aggs/gridsat_WA_-40C_climatology_mean_mf_'+htag1+'.nc' dat1 = xr.open_dataset(msg_folder + p1) #ipdb.set_trace() month1 = dat1['tir'] htag2 = str(h).zfill(2) + 'UTC_1985-1993' p2 = 'aggs/gridsat_WA_-40C_climatology_mean_mf_'+htag2+'.nc' dat2 = xr.open_dataset(msg_folder + p2) month2 = dat2['tir'] for d, tag in [(month1, htag1), (month2,htag2)]: d = d.sel(lon=slice(-79, -74), lat=slice(-12, -7)) simple = d.plot(x='lon', y='lat', col='month', col_wrap=4, cmap='jet', transform=ccrs.PlateCarree(), subplot_kws={'projection': ccrs.PlateCarree()}, vmax=-40, vmin=-65, levels=10, extend='both') for ax in simple.axes.flat: ax.coastlines() ax.gridlines() ax.plot(-77.55, -9.51, 'ko') # ax.set_extent([-17.5, 30, -6, 20]) ax.set_aspect('equal', 'box-forced') plt.savefig(cnst.network_data + '/figs/HUARAZ/mean_t_' + tag + '_small.png', dpi=300) fname = '/home/ck/DIR/cornkle/data/HUARAZ/shapes/riosan_sel_one.shp' shape_feature = ShapelyFeature(Reader(fname).geometries(), ccrs.PlateCarree(), facecolor='none') diff = month1-month2 diff = diff.sel(lon=slice(-79,-74), lat=slice(-12,-7)) simple = diff.plot(x='lon', y='lat', col='month', col_wrap=4, cmap='RdBu_r', transform=ccrs.PlateCarree(), subplot_kws={'projection': ccrs.PlateCarree()}, vmax=5, vmin=-5, levels=10, extend='both') for ax in simple.axes.flat: ax.coastlines() ax.gridlines() # ax.set_extent([-17.5, 30, -6, 20]) ax.set_aspect('equal', 'box-forced') ax.add_feature(shape_feature) ax.add_geometries(Reader(fname).geometries(), ccrs.PlateCarree(), facecolor='white', hatch='xxxx') plt.savefig(cnst.network_data + '/figs/HUARAZ/mean_t_diff_fistlast8years_16UTC_small.png', dpi=300) plt.close('all')
def maskcountries(self, conf, ax=None, regions=["China"], pathkw=dict(facecolor='none', edgecolor='black', linewidth=1.5)): """ 在cartopy中, 对选定的国家进行白化. refer to https://cloud.tencent.com/developer/article/1618341 Args: conf (matplotlib object): matplotlib的contour或contourf绘图返回值. ax (object, optional): Axes instance, if not None then overrides the default axes instance. regions (list, optional): 指定无需白化的国家. Defaults to ["China"]. pathkw (dict, optional): PathPatch关键字参数. Defaults to dict(facecolor='none',edgecolor='black', linewidth=1.0). Returns: clipping path, matplotlib.patches.PathPatch """ #Get current axes if not specified ax = ax or self._check_ax() #Convert region name to upper regions = list(regions) regions = [region.upper() for region in regions] # get shape file shpfile = pkg_resources.resource_filename( 'nmc_met_graphics', "resources/maps/country1.shp") # retrive region geometry reader = Reader(shpfile) countries = reader.records() multipoly, = [ country.geometry for country in countries if country.attributes['CNTRY_NAME'].upper() in regions ] main_geom = sorted(multipoly.geoms, key=lambda geom: geom.area)[-1] path, = geos_to_path(main_geom) plate_carre_data_transform = ccrs.PlateCarree()._as_mpl_transform(ax) for collection in conf.collections: collection.set_clip_path(path, plate_carre_data_transform) # Draw the path of interest. path = PathPatch(path, transform=ccrs.PlateCarree(), **pathkw) return path
def plot_base(self, bous = 1, bmap = None, features = ['land','ocean','lake','river'], gridline = True, lic = True): """ Plot map base Parameters ---------- bous : TYPE, optional DESCRIPTION. The default is 1. bmap : TYPE, optional DESCRIPTION. The default is None. features : TYPE, optional DESCRIPTION. The default is ['land','ocean','lake','river']. gridline : TYPE, optional DESCRIPTION. The default is True. lic : TYPE, optional DESCRIPTION. The default is True. Returns ------- None. """ if self.engine == 'gmt': self.gmt_plot_base(self.region) else: self.fig.set_extent([72, 137, 10, 55]) self.fig.stock_img() self.fig.coastlines() self.fig.add_feature(cfeature.LAND) self.fig.add_feature(cfeature.OCEAN) self.fig.add_feature(cfeature.LAKES) self.fig.add_feature(cfeature.RIVERS) self.fig.gridlines(crs=ccrs.PlateCarree(), draw_labels=True) datapath = Path(Path(catalog.__file__).parent,'data') fname = Path(datapath, 'bou1_4l.shp') f2name = Path(datapath, 'bou2_4l.shp') faults = Path(datapath, 'gem_active_faults.shp') self.fig.add_geometries(Reader(str(faults)).geometries(), ccrs.PlateCarree(),facecolor = 'none', edgecolor='red') self.fig.add_geometries(Reader(str(f2name)).geometries(), ccrs.PlateCarree(), facecolor = 'none', edgecolor='gray', linestyle=':') self.fig.add_geometries(Reader(str(fname)).geometries(), ccrs.PlateCarree(), facecolor = 'none', edgecolor='black')
def addFeatures(fname): f = Reader(fname) for item in f.records(): attributes = item.attributes geometry = item.geometry facecolor, edgecolor, alpha = categorizeBWS_s(attributes, column, categories) feature = ShapelyFeature(geometry, ccrs.PlateCarree(), facecolor=facecolor, edgecolor=edgecolor, alpha=alpha) ax.add_feature(feature)
def make_np_mask(target_header): """Generate mask of cells that are in Redwood National Park""" rdr = Reader(os.path.join("InputData", "nps_boundary", "nps_boundary.shp")) redw_records = [] for x in rdr.records(): if 'Redwood' in x.attributes['UNIT_NAME']: redw_records.append(x) redw_shape_nps = redw_records[0].geometry[0] NAD83_Cali_Albers = pyproj.Proj("+init=EPSG:3310") nps_proj = pyproj.Proj("+init=EPSG:4269") project = partial(pyproj.transform, nps_proj, NAD83_Cali_Albers) redw_shape = transform(project, redw_shape_nps) lower_x = np.array([ target_header['xllcorner'] + i * target_header['cellsize'] for i in range(target_header['ncols']) ]) upper_x = lower_x + target_header['cellsize'] lower_y = np.array([ target_header['yllcorner'] + i * target_header['cellsize'] for i in range(target_header['nrows']) ])[::-1] upper_y = lower_y + target_header['cellsize'] np_array = np.zeros((target_header['nrows'], target_header['ncols'])) for i in range(target_header['nrows']): for j in range(target_header['ncols']): points = [[lower_x[j], lower_y[i]], [upper_x[j], lower_y[i]], [upper_x[j], upper_y[i]], [lower_x[j], upper_y[i]]] cell = geometry.Polygon(points) intersection_area = redw_shape.intersection(cell).area / ( target_header['cellsize'] * target_header['cellsize']) np_array[i, j] = intersection_area np_raster = raster_tools.RasterData( (target_header['nrows'], target_header['ncols']), (target_header['xllcorner'], target_header['yllcorner']), target_header['cellsize'], array=np_array) return np_raster
def shpplt(shp, colors, ax=None, crs=ccrs.PlateCarree(), field='type', numbered=True, **kwargs): """ Plot polygon .shp file from path using variable colors. Requires that .shp file have field with numerical values that will correspond to color. Parameters: shp: Path to .shp file colors: List or dict of colors corresponding to field in .shp file ax: Axes on which to plot polygon crs: Cartopy projection for .shp file field: Name of field with values used for color Retruns: df: Pandas dataframe of attribute table from .shp file """ reader = Reader(shp) # Creates reader object units = reader.records() # Gets records from reader object lst = [] # Set up empty list for unit in units: # Iterate over each object in .shp file # Get type number from attributes to assign color, requires 'type' # field in imported .shp file t = unit.attributes[field] geo = unit.geometry # Get geometry to plot # Plot geometry using field attribute to assign color # If field sequential integers, adapt for Python counting if numbered is True: ax.add_geometries([geo], crs, facecolor=colors[t - 1], **kwargs) # If field non-sequential, use color dictionary elif numbered is False: ax.add_geometries([geo], crs, facecolor=colors[t], **kwargs) # Add attributes to list to create dataframe lst.append(unit.attributes) df = pd.DataFrame.from_records(lst) #create dataframe of attribute table return (df)
def mapa_base(llat, llon): """ Mapa base para graficar las variables """ l_lat = llat l_lon = np.array(llon) % 360 #Pasamos lon en [-180, 180] a [0, 360] states_provinces = cpf.NaturalEarthFeature(category='cultural', name='admin_1_states_provinces_lines', scale='10m', facecolor='none') shp = Reader(natural_earth(resolution='10m', category='cultural', name='admin_1_states_provinces_lines')) countries = shp.records() # Comenzamos la Figura fig = plt.figure(figsize=(6, 8)) proj_lcc = ccrs.PlateCarree() ax = plt.axes(projection=proj_lcc) ax.coastlines(resolution='10m') ax.add_feature(cpf.BORDERS, linestyle='-') #ax.add_feature(states_provinces, edgecolor='gray') for country in countries: if country.attributes['adm0_name'] == 'Argentina': ax.add_geometries( [country.geometry], ccrs.PlateCarree(), edgecolor='black', facecolor='none', linewidth=0.7 ) # ax.add_feature(shape_feature) # Colocamos reticula personalizada gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, linewidth=0.4, color='gray', alpha=0.7, linestyle=':') gl.xlabels_top = False gl.ylabels_right = False gl.xlocator = mticker.FixedLocator(np.linspace(llon[0], llon[1], 7)) gl.ylocator = mticker.FixedLocator(np.linspace(l_lat[0], l_lat[1], 9)) gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER # Extension del mapa ax.set_extent([l_lon[0], l_lon[1], l_lat[0], l_lat[1]], crs=proj_lcc) # Posicion del eje (desplazamos un poco a la izquierda y más abajo) pos1 = ax.get_position() # get the original position pos2 = [pos1.x0 - 0.05, pos1.y0 - 0.06, pos1.width*1.16, pos1.height*1.22] ax.set_position(pos2) # set a new position ax.text(-79., -21., 'Fuente:\n NOAA - GFS', horizontalalignment='left', verticalalignment='top', fontweight='bold', fontsize=13, transform=ccrs.Geodetic()) return fig, ax
def cartoplot_schools(mapsize, shapefile, data): # 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) # set up colormap from matplotlib import cm import matplotlib.colors cmap = cm.get_cmap('seismic_r', 100) norm = matplotlib.colors.Normalize(vmin=min(data['School score']), vmax=max(data['School score'])) color = cmap(norm(data['School score'].values)) # add colorbar n_cmap = cm.ScalarMappable(norm=norm, cmap='seismic_r') n_cmap.set_array([]) cax = fig.add_axes([0.185, 0.15, 0.02, 0.25]) cbar = ax.get_figure().colorbar(n_cmap, cax) # set colorbar label, properties cbar.set_label('School score\n(% proficient)', rotation=0, labelpad=15, y=0.55, ha='left') cbar.ax.tick_params(labelsize=16) cax.yaxis.set_ticks_position('left') text = cax.yaxis.label font = matplotlib.font_manager.FontProperties(family='Helvetica', size=20) text.set_font_properties(font) for tick in cbar.ax.yaxis.get_ticklabels(): tick.set_family('Helvetica') # add shapefile features shape_feature = ShapelyFeature(Reader(shapefile).geometries(), ccrs.epsg(26910), linewidth=2) # Add commute data by zip code for counter, geom in enumerate(shape_feature.geometries()): if data['Area'][counter] < 50: if data['Population'][counter] > 500: ax.add_geometries([geom], crs=shape_feature.crs, facecolor=color[counter], edgecolor='k', alpha=0.8) else: continue # save figure, show figure fig = plt.gcf() plt.savefig('schools_plot.jpg', bbox_inches='tight', dpi=600) plt.show()
def add_river_shapes(ax, city, crs=None): data_dir = Path(__file__).parent.parent / "canvec_250K" city_to_province = { "Toronto": "ON", "Montreal": "QC", "Ottawa-Gatineau": "ON", "Vancouver": "BC", "Calgary": "AB", "Edmonton": "AB", "Winnipeg": "MB", "Halifax": "NS", "Saskatoon": "SK", "Moncton": "NB", "Charlottetown": "PE", "St Johns": "NL" } params = dict(facecolor=feature.COLORS["water"], linewidth=0) for province_dir in data_dir.iterdir(): if province_dir.is_dir( ) and city_to_province[city] in province_dir.name: for f in (province_dir / province_dir.name[:-4]).iterdir(): if f.name.startswith("waterbody_2") and f.name.endswith( ".shp"): ax.add_geometries( Reader(str(f)).geometries(), crs, **params)
def plot_basic_ppi(path, filename, level, shape_rivers, shape_states): """ """ radar = pyart.aux_io.read_gamic(filename) date = pyart.util.datetime_from_grid(radar) str_level = str("%.1f" % radar.fixed_angle["data"][level]) fig = plt.figure(figsize=(8, 7)) ax = fig.add_subplot(111, projection=ccrs.PlateCarree()) display = pyart.graph.RadarMapDisplay(radar) display.plot_ppi_map( "corrected_reflectivity", sweep=level, vmin=0, vmax=70, ax=ax, cmap="dbz", shapefile=path + shape_rivers, shapefile_kwargs={ "facecolor": "None", "edgecolor": "darkblue", "alpha": 0.3, "linewidth": 0.75, }, ) ax.add_geometries( Reader(path + shape_states).geometries(), ccrs.PlateCarree(), linewidth=0.75, facecolor="None", edgecolor="gray", alpha=0.8, ) gl = ax.gridlines( crs=ccrs.PlateCarree(), draw_labels=True, xlocs=np.arange(-70, -50, 1), ylocs=np.arange(-10, 1, 1), ) gl.top_labels = gl.right_labels = False gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER display.plot_range_rings([50, 100, 150, 200, 250], ax=ax, col="lightgray", lw=1) plt.savefig( path + "radar_processing/figs/sipam_ppi/sipam_" + str_level + "_dBZ_" + date.strftime("%Y%m%d%H%M%S") + ".png", bbox_inches="tight", dpi=300, facecolor="None", edgecolor="white", ) plt.close() print("Plotted! " + str(date) + " - " + str_level + "°")
def get_geometries_ocean(name0): """ Get an iterable of Shapely geometries corrresponding to given countries. """ # Using the Natural Earth feature interface provided by cartopy. # You could use a different source, all you need is the geometries. print(name0) shape_records = Reader( shpreader.natural_earth(resolution='110m', category='Physical', name='ocean')).records() geoms = [] names = [] for country in shape_records: try: geoms += country.geometry except TypeError: geoms.append(country.geometry) if name0 == 'MPac': geoms = add_country(geoms, 'Taiwan') if name0 == 'SCSPhi': geoms = add_country(geoms, 'Philippines') for i in range(len(geoms)): names.append(name0) return geoms, ccrs.PlateCarree()._as_mpl_transform, names
def add_china_map_2cartopy(ax, name='province', facecolor='none', edgecolor='c', lw=2, **kwargs): """ Draw china boundary on cartopy map. :param ax: matplotlib axes instance. :param name: map name. :param facecolor: fill color, default is none. :param edgecolor: edge color. :param lw: line width. :return: None """ # map name names = {'nation': "bou1_4p", 'province': "bou2_4p", 'county': "BOUNT_poly", 'river': "hyd1_4l", 'river_high': "hyd2_4l"} # get shape filename shpfile = pkg_resources.resource_filename( 'dk_met_graphics', "resources\\maps\\" + names[name] + ".shp") # add map ax.add_geometries( Reader(shpfile).geometries(), ccrs.PlateCarree(), facecolor=facecolor, edgecolor=edgecolor, lw=lw, **kwargs)
def plot_breakup_images(paths_2007, paths_2012, paths_2019, coastline_path, lon_min_MOD, lon_max_MOD, lat_min_MOD, lat_max_MOD, fontsz, figsz): ''' This function plots n images from 2007, 2012, and 2019 Kotzebue Sound breakups in a 3xn grid ''' gdal.UseExceptions() cols = len(paths_2007) coastline = ShapelyFeature(Reader(coastline_path).geometries(),ccrs.PlateCarree()) #extract coordinate system from first file to be used as projection of all subplots fname = paths_2007[0] ds = gdal.Open(fname) 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(nrows=3, ncols=cols, figsize=figsz, subplot_kw=subplot_kw, facecolor='w') fig.suptitle('Satellite Imagery of the Sea Ice Breakup Process in Kotzebue Sound',y=0.95,fontsize=40) for idx in np.arange(0,cols): plot_MODIS_geotiff(axx[0,idx], paths_2007[idx], coastline, lon_min_MOD, lon_max_MOD, lat_min_MOD, lat_max_MOD ) plot_MODIS_geotiff(axx[1,idx], paths_2012[idx], coastline, lon_min_MOD, lon_max_MOD, lat_min_MOD, lat_max_MOD ) plot_MODIS_geotiff(axx[2,idx], paths_2019[idx], coastline, lon_min_MOD, lon_max_MOD, lat_min_MOD, lat_max_MOD ) axx[0,idx].add_patch(patches.Ellipse(xy=(-162.6139,66.8968), width=1.1, height=0.44, edgecolor='r', linewidth=4, transform=ccrs.PlateCarree(), facecolor='none',zorder=400)) axx[1,idx].add_patch(patches.Ellipse(xy=(-162.6139,66.8968), width=1.1, height=0.44, edgecolor='r', linewidth=4, transform=ccrs.PlateCarree(), facecolor='none',zorder=400)) axx[2,idx].add_patch(patches.Ellipse(xy=(-162.6139,66.8968), width=1.1, height=0.44, edgecolor='r', linewidth=4, transform=ccrs.PlateCarree(), facecolor='none',zorder=400)) for idx in np.arange(0,cols-1): for row in np.arange(0,3): con = ConnectionPatch(xyA=(1,0.5), coordsA=axx[row,idx].transAxes, xyB=(0,0.5), coordsB=axx[row,idx+1].transAxes, arrowstyle='->',linewidth=6,mutation_scale=50) fig.add_artist(con) axx[0,0].set_title('May 24',fontsize=fontsz) axx[0,1].set_title('June 1',fontsize=fontsz) axx[0,2].set_title('June 5',fontsize=fontsz) axx[0,3].set_title('June 11',fontsize=fontsz) axx[1,0].set_title('May 24',fontsize=fontsz) axx[1,1].set_title('May 31',fontsize=fontsz) axx[1,2].set_title('June 7',fontsize=fontsz) axx[1,3].set_title('June 16',fontsize=fontsz) axx[2,0].set_title('April 23',fontsize=fontsz) axx[2,1].set_title('May 10',fontsize=fontsz) axx[2,2].set_title('May 16',fontsize=fontsz) axx[2,3].set_title('May 25',fontsize=fontsz) plt.figtext(x=0.1,y=0.745,s='2007',rotation=90,fontsize=40) plt.figtext(x=0.1,y=0.475,s='2012',rotation=90,fontsize=40) plt.figtext(x=0.1,y=0.21,s='2019',rotation=90,fontsize=40)
def plot_polygons(regions): """ extract the polygon coordinate and plot it on a worldmap :param regions: list of ISO abreviations for polygons :return png: map_graphic.png """ from cartopy.io.shapereader import Reader from cartopy.feature import ShapelyFeature from os.path import curdir, abspath from flyingpigeon import config DIR_SHP = config.shapefiles_dir() if type(regions) == str: regions = list([regions]) fname = join(DIR_SHP, "countries.shp") geos = Reader(fname).geometries() records = Reader(fname).records() LOGGER.debug('') fig = plt.figure(figsize=(10, 10), facecolor='w', edgecolor='k') # dpi=600, projection = ccrs.Orthographic(central_longitude=0.0, central_latitude=0.0, globe=None) # Robinson() ax = plt.axes(projection=projection) for r in records: geo = geos.next() if r.attributes['ISO_A3'] in regions: shape_feature = ShapelyFeature(geo, ccrs.PlateCarree(), edgecolor='black') ax.add_feature(shape_feature) ax.coastlines() # ax.set_global() o1, map_graphic = mkstemp(dir=abspath(curdir), suffix='.png') fig.savefig(map_graphic) plt.close() return map_graphic
def plot_may2019_image(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 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) #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.018, dy=0.03, width=0.01, facecolor='k',transform=axx.transAxes,zorder=400));
def plot_cmaq(monthly_tot,var_tot,title_2,cmap,vmaxs,vmins,crs_new,show,add_epa,version,div,shaped): for i in range(0,len(monthly_tot)): #for i in range(1): # set var for plot var= var_tot[i] data= np.asarray(monthly_tot[i]) if var == 'RAINC': pass else: if i<len(cmaq_var): plon,plat = lon,lat else: plon,plat = wlon,wlat # make fig object fig, axs = plt.subplots(subplot_kw={'projection': crs_new},figsize=(6, 6)) #set up data for plotting via levels vmax,vmin=vmaxs[i],vmins[i] #for i in range(1): levels = np.arange(vmin, vmax, (vmax-vmin)/10) # set boundary as outer extent by making a matplotlib path object and adding that geometry if shaped: 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 if div==False: cs=plt.pcolormesh(plon,plat,data,cmap= cmap , transform=crs_new, vmin=vmin,vmax=vmax) if div == True: divnorm = colors.DivergingNorm(vmin=vmin, vcenter=0, vmax= vmax) cs=plt.pcolormesh(plon,plat,data,cmap= cmap , transform=crs_new, vmin=vmin,vmax=vmax, norm=divnorm) #for i in range(1): # add landmarks with scatterplot midway= -87.7522,41.7868 ohare = -87.9073, 41.9842 loop = -87.6251,41.8786 axs.annotate(xy=midway,s="*",color='white') axs.annotate(xy=ohare,s="*",color='white') axs.annotate(xy=loop,s="*",color='white') # set axes extents from shapefile x=[chi_shapefile.bounds.minx.min(), chi_shapefile.bounds.maxx.max()] y=[chi_shapefile.bounds.miny.min(), chi_shapefile.bounds.maxy.max()] # if shaped: axs.set_extent([x[0],x[1],y[0],y[1]],crs= crs_new) else: axs.set_extent([x[0]-.3,x[1]+.3,y[0]-.3,y[1]+.3],crs= crs_new) # title axs.set_title(var+title_2) #add colorbar and label cbar=plt.colorbar(cs,boundaries=levels,shrink = 0.5) cbar.set_ticks(levels) # add state lines states_provinces = cfeature.NaturalEarthFeature(category='cultural',name='admin_1_states_provinces_lines',scale='50m',facecolor='none') # land = cfeature.NaturalEarthFeature('physical', 'lakes', '10m', edgecolor='black', facecolor='none') axs.add_feature(land, edgecolor='black') axs.add_feature(states_provinces, edgecolor='black') #add epa monitors if its CMAQ if add_epa == True: if i < len(cmaq_var): try: axs.scatter(epa_avgs_latlon[i]['Longitude'],epa_avgs_latlon[i]['Latitude'],c=epa_avgs_latlon[i]['Arithmetic Mean'],vmin = vmin, vmax= vmax,s=75, cmap = cmap,edgecolors = 'black') except: pass #savefig plt.savefig(var+version+'v7.png',transparent=True) if show == True: plt.show()
def add_shapefile(ax, shapefile, projection=ccrs.PlateCarree(), facecolor='none', edgecolor='black'): shape_feature = ShapelyFeature(Reader(shapefile).geometries(), projection) ax.add_feature(shape_feature, facecolor=facecolor, edgecolor=edgecolor) return ax
def plot_polygons(regions, file_extension='png'): """ extract the polygon coordinate and plot it on a worldmap :param regions: list of ISO abreviations for polygons :return png: map_graphic.png """ from cartopy.io.shapereader import Reader from cartopy.feature import ShapelyFeature from numpy import mean, append from blackswan import config DIR_SHP = config.shapefiles_path() if type(regions) == str: regions = list([regions]) fname = join(DIR_SHP, "countries.shp") geos = Reader(fname).geometries() records = Reader(fname).records() central_latitude = [] central_longitude = [] for r in records: geo = geos.next() if r.attributes['ISO_A3'] in regions: x, y = geo.centroid.coords.xy central_longitude.append(x[0]) central_latitude.append(y[0]) fig = plt.figure(figsize=(20, 10)) projection = ccrs.Orthographic(central_longitude=mean(central_longitude), central_latitude=mean(central_latitude), globe=None) # Robinson() ax = plt.axes(projection=projection) geos = Reader(fname).geometries() records = Reader(fname).records() for r in records: geo = geos.next() if r.attributes['ISO_A3'] in regions: shape_feature = ShapelyFeature(geo, ccrs.PlateCarree(), edgecolor='black', color='coral') ax.add_feature(shape_feature) ax.coastlines() ax.gridlines() ax.stock_img() # ax.set_global() map_graphic = fig2plot(fig=fig, file_extension=file_extension) plt.close() return map_graphic
def main(): # Iniciando a projeção e suas dimensões lat/lon ax = plt.axes(projection=ccrs.PlateCarree()) # coords = (-54, -47, -25.8, -29.4) coords = (-50, -48, -26, -29.4) ax.set_extent(coords) # ax.set_yticks((-25.8, -27.0, -28.2, -29.4)) ax.gridlines(draw_labels=True) # Shapefiles que vão gerar os limites territoriais. brasil = 'analysis/cartopy/shapefiles/Brasil-POLYGON.shp' sc = 'analysis/cartopy/shapefiles/SC-POLYGON.shp' laguna = 'analysis/cartopy/shapefiles/DestaqueLaguna-POLYGON.shp' lagoas = 'analysis/cartopy/shapefiles/LagoasComplexoLagunar-POLYGON.shp' # Vamos fazer uma lista para iterar um loop com a função add_geometries() shapes = [brasil, sc, laguna, lagoas] ax.stock_img() # for loop para adicionar os shapes à figura for item in shapes: if item is lagoas: ax.add_geometries(Reader(item).geometries(), ccrs.PlateCarree(), facecolor='skyblue', edgecolor='black') else: ax.add_geometries(Reader(item).geometries(), ccrs.PlateCarree(), facecolor='beige', edgecolor='black') # p = patches.Rectangle( # (-48.9, -28.55), 0.2, 0.15, # fill = False, color = 'red', # zorder = 6, lw = 3.0, ls = '-' # ) # ax.add_patch(p) plt.show()
def plot_continental_polygons(self, ax, facecolor=None, edgecolor='none', alpha=0.1): print('Plotting continental polygons...') shape_feature = ShapelyFeature( Reader(continental_polygons_output_basename).geometries(), ccrs.PlateCarree(), edgecolor=edgecolor) ax.add_feature(shape_feature, facecolor=facecolor, alpha=alpha)
def create_map(fig): shp_path = r'/mnt/e/公众号/可视化/cartopy/China_shp_lqy/' # --创建画图空间 proj = ccrs.LambertConformal(central_longitude=110, central_latitude=35, standard_parallels=(30, 60)) # 创建坐标系 ax = fig.subplots(1, 1, subplot_kw={'projection': proj}) # --设置shp provinces = cfeat.ShapelyFeature( Reader(shp_path + 'province.shp').geometries(), ccrs.PlateCarree(), edgecolor='k', facecolor='none', ) ax.add_feature(provinces, linewidth=0.6, zorder=2) # --设置范围 ax.set_extent([80, 135, 15, 55], crs=ccrs.PlateCarree()) # --关闭边框 ax.spines['geo'].set_visible(False) # --设置刻度 ax.tick_params(axis='both', labelsize=5, direction='out', labelbottom=False, labeltop=False, labelleft=False, labelright=False) # --设置小地图 left, bottom, width, height = 0.675, 0.13, 0.23, 0.27 ax2 = fig.add_axes([left, bottom, width, height], projection=ccrs.PlateCarree()) provinces = cfeat.ShapelyFeature( Reader(shp_path + 'province.shp').geometries(), ccrs.PlateCarree(), edgecolor='k', facecolor='gray', ) ax2.add_feature(provinces, linewidth=0.6, zorder=2) ax2.set_extent([105, 125, 0, 25], crs=ccrs.PlateCarree()) return ax
def add_country(geoms, name): shape_records = Reader( natural_earth(resolution='110m', category='cultural', name='admin_0_countries')).records() for country in shape_records: if country.attributes['NAME_LONG'] in name: try: geoms += country.geometry except TypeError: geoms.append(country.geometry) return geoms
def get_country_geom(name_list): country_shapes = Reader( natural_earth(resolution='10m', category='cultural', name='admin_0_countries')).records() geoms = [] for name in name_list: for shape_temp in country_shapes: if name == shape_temp.attributes['NAME_EN']: print('Selecting: {}'.format(name)) geoms.append(shape_temp.geometry) return geoms
new_d14c_cube.data = d14c_data_for_cube new_dpco2_cube.data = dpco2_data_for_cube new_d14c_cube.coord('time').points = (d14c_cube.coord('time').points-11)/100 new_dpco2_cube.coord('time').points = (d14c_cube.coord('time').points-11)/100 new_d14c_cube.long_name = d14c_cube.long_name new_dpco2_cube.long_name = dpco2_cube.long_name new_d14c_cube.standard_name = d14c_cube.standard_name new_dpco2_cube.standard_name = dpco2_cube.standard_name new_d14c_cube.units = d14c_cube.units new_dpco2_cube.units = dpco2_cube.units new_d14c_cube.var_name = d14c_cube.var_name new_dpco2_cube.var_name = dpco2_cube.var_name shpfilename = natural_earth(resolution='110m', category='physical', name='land') reader = Reader(shpfilename) continents = reader.records() new_d14c_cube.coord('latitude').guess_bounds() new_d14c_cube.coord('longitude').guess_bounds() new_dpco2_cube.coord('latitude').guess_bounds() new_dpco2_cube.coord('longitude').guess_bounds() continent_geometries = reader.geometries() # NB. Switched from using records() all_continents_geometry = cascaded_union(list(continent_geometries)) area_weights = geometry_area_weights(new_d14c_cube, all_continents_geometry) land_mask = np.where(area_weights > 0, True, False) new_d14c_cube.data = np.ma.array(new_d14c_cube.data, mask=land_mask) area_weights = geometry_area_weights(new_dpco2_cube, all_continents_geometry) land_mask = np.where(area_weights > 0, True, False) new_dpco2_cube.data = np.ma.array(new_dpco2_cube.data, mask=land_mask)
from cartopy.feature import ShapelyFeature import cartopy.feature as cfeature import os plt.clf() #ax = geo_plots.add_map(bbox=(-89,-85,27.5,31)) ax = geo_plots.add_map(bbox=(-90, -84, 27.5, 31)) #land_10m = cfeature.NaturalEarthFeature('physical','land','50m',\ # edgecolor='face',facecolor='0.75') ##ax.add_feature(cfeature.LAND, facecolor='0.75') #ax.add_feature(land_10m) #if bbox not specified, this will use map bounds from bna 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 ['100m','500m','1000m']: shape_feature = ShapelyFeature(geo,ccrs.PlateCarree(), facecolor='none') ax.add_feature(shape_feature) #add particles at one time t = datetime.datetime(2016, 9, 21, 1) filename = 'gulf_tamoc.nc' ax = geo_plots.contour_particles(ax,filename,t,levels=[0.1, 0.4, 0.6, 1]) #ax = geo_plots.plot_particles(ax,filename,t,depth=0,color='b') #add initial location