def plot_variable(self, variable, variable_label, model_label): fig, ax = plt.subplots(subplot_kw={'projection': ccrs.PlateCarree()}, constrained_layout=True) CS = plt.contourf(self.LON, self.LAT, self.field, self.num_levels, cmap=self.colormap, transform=ccrs.PlateCarree()) coastname = './Shapefiles/Costa.shp' #coastlines_10m = cfeature.NaturalEarthFeature('physical', 'coastline', '10m') coastlines_10m = ShapelyFeature(Reader(coastname).geometries(), ccrs.epsg(25831), linewidth=1, facecolor='None', edgecolor='black') ax.add_feature(coastlines_10m, facecolor='None', edgecolor='black') filename = './Shapefiles/AMB31N.shp' AMB_feature = ShapelyFeature(Reader(filename).geometries(), ccrs.epsg(25831), linewidth=1, facecolor='None', edgecolor='black') ax.add_feature(AMB_feature) cbar = fig.colorbar(CS) cbar.ax.set_ylabel(variable_label, size=12) plt.savefig(pathout + variable + "_" + model_label + "_map.png") 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 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 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 mask_china_region(ax, facecolor='white', include_sea=False): china_shapefile_path = f'{os.path.dirname(os.path.realpath(__file__))}/../shapefiles/china_without_islands.shp' extent = ax.get_extent() frame = Polygon([(extent[0], extent[2]), (extent[1], extent[2]), (extent[1], extent[3]), (extent[0], extent[3]), (extent[0], extent[2])]) shapes = cascaded_union( list(ShapeReader(china_shapefile_path).geometries())) if include_sea: for polygon in shapes: if polygon.area > 900: china_mainland = polygon break mask_polygon = frame.difference( china_mainland.union(get_china_territorial_sea_polygon())) if type(mask_polygon) != MultiPolygon: mask_polygon = MultiPolygon([mask_polygon]) else: mask_polygon = MultiPolygon([frame.difference(shapes)]) mask = ShapelyFeature(mask_polygon, ccrs.PlateCarree(), edgecolor='none', facecolor=facecolor) ax.add_feature(mask)
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 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 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_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 plot(lon, lat, values, vmin, vmax, title, pdf, cmap=RdBu_10_r, colorbar=True): proj = ccrs.PlateCarree() fig = plt.figure(figsize=(12, 8)) ax = plt.axes(projection=proj) ax.set_extent([73, 135, 15, 55], crs=proj) ax.gridlines(crs=proj, draw_labels=True, linewidth=1, color='k', alpha=0.5, linestyle='--') if os.path.isfile('/opt/china-shapefiles/shapefiles/china.shp'): china = ShapelyFeature(ShapeReader( '/opt/china-shapefiles/shapefiles/china.shp').geometries(), proj, edgecolor='grey', facecolor='none') ax.add_feature(china) else: print( 'You can run the following command to get China official shapefiles.' ) print('# cd /opt') print('# git clone https://github.com/dongli/china-shapefiles') ax.add_feature(COASTLINE.with_scale('50m'), linewidth=0.5) p = ax.scatter(lon, lat, s=2.0, c=values, vmin=vmin, vmax=vmax, cmap=cmap.mpl_colormap) if colorbar: fig.colorbar(p, orientation='horizontal', extend='both', spacing='proportional', aspect=40, pad=0.05) ax.set_title(title) pdf.savefig() plt.close()
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 addFeatures(features): for item in features.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 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 plot_shapes(levels=True, max_level=5): ax = plt.axes(projection=ccrs.Robinson()) if levels: for level in range(max_level + 1): fname = r'/Users/shrutinath/Attribution/gadm36_levels_shp/gadm36_%i.shp' % level shape_feature = ShapelyFeature(Reader(fname).geometries(), ccrs.PlateCarree(), edgecolor='black') ax.add_feature(shape_feature) else: fname = r'/Users/shrutinath/Attribution/TM_WORLD_BORDERS-0.3/TM_WORLD_BORDERS-0.3.shp' shape_feature = ShapelyFeature(Reader(fname).geometries(), ccrs.PlateCarree(), edgecolor='black') ax.add_feature(shape_feature) plt.show()
def on_pbOverlay_click(self): """ EXPERIMENTAL Overlay a specific geometry on maps """ fname = open_file_dialog(dialog_type = 'open_specific', data_format = 'Shapefile', extension = 'shp') # If there is no selection if fname == '': return None # If file does not exists if os.path.exists(fname) is False: return None # Open file spatial_reference = self.get_shapefile_spatial_reference(fname) # Get projection from first data variable for key in self.ts.data.data_vars: proj4_string = getattr(self.ts.data, key).crs break # If projection is Sinusoidal srs = get_projection(proj4_string) if srs.GetAttrValue('PROJECTION') == 'Sinusoidal': # Get ellipsoid/datum parameters globe=ccrs.Globe(ellipse=None, semimajor_axis=spatial_reference.GetSemiMajor(), semiminor_axis=spatial_reference.GetSemiMinor()) self.shapefile_projection = ccrs.Sinusoidal(globe=globe) #ccrs.CRS(spatial_reference.ExportToProj4()) else: globe = ccrs.Globe(ellipse='WGS84') self.shapefile_projection = ccrs.Mollweide(globe=globe) try: shape_feature = ShapelyFeature(cReader(fname).geometries(), self.shapefile_projection, facecolor='none') for _axis in [self.left_p, self.right_p]: _axis.add_feature(shape_feature, edgecolor='gray') except: return None self.fig.canvas.draw() self.fig.canvas.flush_events()
def new_artist(self, geometry, color, z_order=None): kwargs = dict(crs=self._display.crs) if z_order is not None: kwargs['zorder'] = z_order if isinstance(color, tuple): kwargs['ec'] = color[0] kwargs['fc'] = color[1] else: kwargs['color'] = color artist = self._display.axes.add_feature( ShapelyFeature([geometry], **kwargs)) if z_order is None: artist.set_animated(True) return artist
def mask_outside_shapes(shapefile_path, ax): extent = ax.get_extent() frame = Polygon([(extent[0], extent[2]), (extent[1], extent[2]), (extent[1], extent[3]), (extent[0], extent[3]), (extent[0], extent[2])]) shapes = cascaded_union(list(ShapeReader(shapefile_path).geometries())) mask = ShapelyFeature(MultiPolygon([frame.difference(shapes)]), ax.projection, edgecolor='none', facecolor='white') ax.add_feature(mask)
def plot(self, timeidx=0, extent=None, pathfig=None): """快速绘图""" import cartopy.crs as ccrs from cartopy.io.shapereader import Reader from cartopy.feature import ShapelyFeature import matplotlib.pyplot as plt plt.rcParams.update({'font.size': 16}) plt.figure(figsize=(12, 8)) ax = plt.axes(projection=ccrs.PlateCarree()) extent = (73, 135, 15, 56) if extent is None else extent ax.set_extent(extent) ax.set_xlim(extent[0], extent[1]) ax.set_ylim(extent[2], extent[3]) # 加中国地图 src_dir = os.path.dirname(os.path.realpath(__file__)) shp = os.path.realpath(os.path.join(src_dir, "cn-shp-data/cnhimap.shp")) fea = ShapelyFeature(Reader(shp).geometries(), ccrs.PlateCarree(), facecolor="none") ax.add_feature(fea, edgecolor='k', lw=0.8) # 绘制填色图 levels = np.array([2.5, 10, 20, 30]) colors = ("#ffffff", "#3dba3d", "#61b8ff", "#1e6eeb", "#fa00fa", "#800040") var = self.crain[timeidx] var = var.where(~np.isnan(var), 0) pc = var.plot.contourf(ax=ax, levels=levels, colors=colors, extend="both", add_colorbar=False) cb = plt.colorbar(pc, fraction=0.02, pad=0.01) cb.ax.xaxis.set_tick_params(direction='in') cb.ax.yaxis.set_tick_params(direction='in') # 网格线 gl = ax.gridlines(draw_labels=True, x_inline=False, y_inline=False, linestyle=":") gl.top_labels = False gl.right_labels = False plt.tight_layout() if pathfig is None: plt.show() else: plt.savefig(pathfig)
def make_choropleth(ax, df, var=None, dict_colors=None): """ makes a choropleth map from """ from shapely.geometry import Point, LineString import cartopy.crs as ccrs from cartopy.feature import ShapelyFeature for i, row in df.iterrows(): v = row.loc[var] if v == 'missing': color = dict_colors[v] geom = row.geometry sp = ShapelyFeature([geom], ccrs.PlateCarree(), edgecolor='none', facecolor=color, lw=0) else: color = dict_colors[v] geom = row.geometry sp = ShapelyFeature([geom], ccrs.PlateCarree(), edgecolor='k', facecolor=color, lw=0.5) ax.add_feature(sp)
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 main(): fig = plt.figure() proj = ccrs.LambertConformal(central_longitude=-95, central_latitude=38, \ false_easting=-0.0, false_northing=0.0, \ standard_parallels=(33,45), \ globe=None) ax = fig.add_subplot(1, 1, 1, projection=proj) # ax.set_xlim(-170,170) # ax.set_ylim(-80,80) ax.set_extent([-119, -92, 22.8, 52], crs=ccrs.PlateCarree()) # Put a background image on for nice sea rendering. # ax.stock_img() # Create a feature for States/Admin 1 regions at 1:50m from Natural Earth # states_provinces = cfeature.NaturalEarthFeature( # category='cultural', # name='admin_1_states_provinces_lines', # scale='50m', # facecolor='none') SOURCE = 'Natural Earth' LICENSE = 'public domain' # ax.add_feature(cfeature.LAND) # ax.add_feature(cfeature.COASTLINE) fname = r'D:/Krishna/projects/vwc_from_radar/data/usa_shapefile/west_usa/west_usa_shapefile_lcc.shp' shape_feature = ShapelyFeature(Reader(fname).geometries(), ccrs.LambertConformal(), edgecolor='black') ax.add_feature(shape_feature, facecolor="None") # ax.add_feature(cfeature.) # ax.add_feature(states_provinces, edgecolor='gray') # Add a text annotation for the license information to the # the bottom right corner. # text = AnchoredText(r'$\mathcircled{{c}}$ {}; license: {}' # ''.format(SOURCE, LICENSE), # loc=4, prop={'size': 12}, frameon=True) # ax.add_artist(text) plt.show()
def map_data(data, lat, lon, shapefiles='none'): # gis_layers a list of filenames # first, check that lat, lon, and data all same size if lat.shape != lon.shape: print 'Lat and lon data shape do not match' elif lat.shape != data.shape: print 'Lat/lon & data shape do not match' # set up figures and axes plt.figure(figsize=[15, 15]) if shapefiles == 'none': imagery = MapQuestOSM() ax = plt.axes(projection=imagery.crs) ax.add_image(imagery, 14) else: ax = plt.axes( projection=ccrs.PlateCarree()) # note to self:put in UTM 18/19 ax.set_extent( (lon.min() - .05, lon.max() + .05, lat.min(), lat.max() + .05)) # if there are shapefiles, read in and display if shapefiles != 'none': for file in shapefiles: shape_feature = ShapelyFeature(Reader(file).geometries(), ccrs.PlateCarree(), facecolor='none', edgecolor='black') ax.add_feature(shape_feature) # define colormap cmap = matplotlib.cm.OrRd bounds = np.linspace(round((data.mean() - 2 * data.std())), round((data.mean() + 2 * data.std())), 13) norm = matplotlib.colors.BoundaryNorm(bounds, cmap.N) # plot plotHandle = ax.scatter(lon, lat, c=data, s=150, transform=ccrs.Geodetic(), cmap=cmap, norm=norm) return ax, plotHandle
def plot_topologies(self, ax, facecolor='default', edgecolor='w', alpha=0.2): print('Plotting topologies...') for record in Reader(topology_output_basename).records(): #print(record.attributes) fc = facecolor if facecolor == 'default': fc = plate_tectonic_utils.get_colour_by_plateid( int(record.attributes['PLATEID1'])) shape_feature = ShapelyFeature([record.geometry], ccrs.PlateCarree(), edgecolor=edgecolor) ax.add_feature(shape_feature, facecolor=fc, alpha=alpha)
def on_pbOverlay_click(self): """ EXPERIMENTAL Overlay a specific geometry on maps """ fname = open_file_dialog(dialog_type = 'open_specific', data_format = 'Shapefile', extension = 'shp') # If there is no selection if fname == '': return None # If file does not exists if os.path.exists(fname) is False: return None # Open file spatial_reference = self.get_shapefile_spatial_reference(fname) # Get ellipsoid/datum parameters globe=ccrs.Globe(ellipse=None, semimajor_axis=spatial_reference.GetSemiMajor(), semiminor_axis=spatial_reference.GetSemiMinor()) self.shapefile_projection = ccrs.Sinusoidal(globe=globe) #ccrs.CRS(spatial_reference.ExportToProj4()) from IPython import embed ; ipshell = embed() try: shape_feature = ShapelyFeature(cReader(fname).geometries(), self.shapefile_projection, facecolor='none') for _axis in [self.ax]: _axis.add_feature(shape_feature, edgecolor='gray') except: return None self.fig.canvas.draw() self.fig.canvas.flush_events()
def shpplt_simple(shp, ax=None, crs=ccrs.PlateCarree(), **kwargs): """ Plot .shp file from path using uniform colors/style Parameters: shp: Path to .shp file ax: Axes on which to plot polygon crs: Cartopy projection for .shp file Retruns: ax: Axes with .shp file plotted """ if ax is None: ax = plt.gca() # Convert .shp file to Shapely Feature feature = ShapelyFeature(Reader(shp).geometries(), crs, **kwargs) ax.add_feature(feature) return (ax)
def cartoplot_trees(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([-125, -117, 30, 45], crs=ccrs.Geodetic()) ax.add_image(stamen_terrain, 6, zorder=0) # add shapefile features shape_feature = ShapelyFeature(Reader(shapefile).geometries(), ccrs.epsg(26910), linewidth=1, facecolor=(1, 1, 1, 0), edgecolor=(0.3, 0.3, 0.3, 1)) ax.add_feature(shape_feature, zorder=1) plt.show()
def plot(self, xar): plt.close() self.fig = plt.figure(**self.fig_kws) self.savefig = self.fig.savefig ax = plt.axes(projection=self.proj) states_provinces = cfeature.NaturalEarthFeature( category='cultural', name='admin_1_states_provinces_lines', scale='50m', facecolor='none') countries = cfeature.NaturalEarthFeature( category='cultural', name='admin_0_boundary_lines_land', scale='50m', facecolor='none') rivers = cfeature.NaturalEarthFeature(scale='50m', category='physical', name='rivers_lake_centerlines', edgecolor='blue', facecolor='none') ax.add_feature(countries, edgecolor='grey') ax.coastlines('50m') #ax.add_feature(states_provinces, edgecolor='gray') ax.add_feature(rivers, edgecolor='blue') if self.kwargs.get('drainage_baisins', True): sf = Reader( "../data/drainage_basins/Major_Basins_of_the_World.shp") shape_feature = ShapelyFeature(sf.geometries(), self.transform, edgecolor='black') ax.add_feature(shape_feature, facecolor='none', edgecolor='green') xar.plot(transform=self.transform, ax=ax, subplot_kws={'projection': self.proj}) self.ax = ax
def get_china_ax(fig=None, subplot=111, min_lon=73, max_lon=135, min_lat=15, max_lat=55, proj=None): if proj == None: proj = ccrs.PlateCarree() if fig: ax = fig.add_subplot(subplot, projection=proj) else: ax = plt.subplot(subplot, projection=proj) ax.set_extent([min_lon, max_lon, min_lat, max_lat], crs=proj) gl = ax.gridlines(crs=proj, draw_labels=True, linewidth=1, color='k', alpha=0.5, linestyle='--') gl.right_labels = False gl.top_labels = False if os.path.isfile('/opt/china-shapefiles/shapefiles/china.shp'): china = ShapelyFeature(ShapeReader( '/opt/china-shapefiles/shapefiles/china.shp').geometries(), proj, linewidth=0.1, edgecolor='grey', facecolor='none') ax.add_feature(china) else: print( 'You can run the following command to get China official shapefiles.' ) print('# cd /opt') print('# git clone https://github.com/dongli/china-shapefiles') ax.add_feature(COASTLINE.with_scale('50m'), linewidth=0.5) return ax
def plot(s): proj = ccrs.PlateCarree() ax = plt.axes(projection=proj) ax.set_extent((s.bounds[0], s.bounds[2], s.bounds[1], s.bounds[3]), crs=ccrs.PlateCarree()) shape_feature = ShapelyFeature([s], ccrs.PlateCarree(), facecolor='#AAFFAA', edgecolor='k') ax.add_feature(shape_feature) gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, linewidth=2, color='gray', alpha=0.5, linestyle='--') gl.xlabels_top = False gl.ylabels_left = False gl.xlabel_style = {'size': 10, 'color': 'black'} gl.ylabel_style = {'size': 10, 'color': 'black'} return gl
def doc_distribution_subplots(): nr, nc = 2, 2 fig, axs = plt.subplots(nr, nc) doc_fp = r'I:\Qinghai_Tibet_Plateau\GlcAnysis\SiteData\观测数据\GlcDOC\GlcDOC.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' } scatters = [] index = 0 for i in range(nr): for j in range(nc): sample_type = sample_type_list[index] data_type = doc_data[doc_data.Type==sample_type] lons, lats, doc = data_type.CorrPt_x, data_type.CorrPt_y, data_type.DOC cmap = mpl.cm.seismic axs[i, j].scatter(lons, lats, doc, cmap=cmap, vmin=0.15, vmax=2.7, transform=ccrs.PlateCarree(), zorder=7) axs[i, j].annotate(sample_type_dict[sample_type], xy=(10, 10), xycoords='axes points', fontsize=14, zorder=8) tp_fp = r'I:\Qinghai_Tibet_Plateau\青藏高原范围与界线数据\DBATP\DBATP\DBATP_Polygon.shp' tp_shape_feature = ShapelyFeature(Reader(tp_fp).geometries(), ccrs.PlateCarree(), facecolor="#F6F7FC") # facecolor='#F6F7FC' axs[i, j].add_feature(cfeature.LAND, zorder=1) axs[i, j].add_feature(cfeature.OCEAN, zorder=2) axs[i, j].add_feature(cfeature.COASTLINE, zorder=3) # ax.add_feature(cfeature.BORDERS, linestyle='-') axs[i, j].add_feature(cfeature.LAKES, alpha=0.5, zorder=4) axs[i, j].add_feature(cfeature.RIVERS, zorder=5) # ax.add_feature(states_provinces, edgecolor='gray') axs[i, j].add_feature(tp_shape_feature, edgecolor='gray', zorder=6) plt.show()