def class_spatial_plot(self): factor = 1.1 delta = 3 / 2 * self.grid_size * factor stamen_terrain = cimgt.Stamen('terrain-background') fig = plt.figure(figsize=(8, 8)) ax = fig.add_subplot(projection=stamen_terrain.crs) ax.set_extent([ self.centre[1] + delta, self.centre[1] - delta, self.centre[0] - delta, self.centre[0] + delta ], ccrs.PlateCarree()) ax.add_image(stamen_terrain, 8) for A in self.A_location: ax.plot(A[1][1], A[1][0], marker='o', color=self.c1, markersize=self.marker_size, alpha=1.0, transform=ccrs.Geodetic()) for B in self.B_location: ax.plot(B[1][1], B[1][0], marker='o', color=self.c4, markersize=self.marker_size, alpha=1.0, transform=ccrs.Geodetic()) for C in self.C_location: ax.plot(C[1][1], C[1][0], marker='o', color=self.c5, markersize=self.marker_size, alpha=1.0, transform=ccrs.Geodetic()) ring_list = [ self._gen_ring(self.c_dict["grid_" + str(i)][8]["coordinates"]) for i in range(9) ] ax.add_geometries(ring_list, ccrs.PlateCarree(), facecolor='none', edgecolor='black') ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True) map_name = "_".join([ self.prefix, "spatial", self.method, self.parameter, self.comp_with, self.loc_name, self.day, str(self.span) ]) map_name = self.plot_dir + map_name + ".png" plt.savefig(map_name)
def plot_line_with_boxes(x0,x1,y0,y1,BOXESX,BOXESY,lats,lons,fig,colours='RdBu',palette='forwards'): '''Takes a line from (x0,y0) to (x1,y1) which has been segmented into boxes with corners given by the arrays BOXESX and BOXESY. These arrays should be created by the 'segment line to boxes' function. All units should be lat/lon.''' coords1 = (y0,x0) coords2 = (y1,x1) Len = geopy.distance.distance(coords1, coords2).m # get vectors with length 1m parallel and perpendicular to the line linevector = np.array([x1-x0,y1-y0]) stamen_terrain = cimgt.Stamen('terrain-background') ax1 = fig.add_axes([0.125,0.15,0.75,0.75],projection=stamen_terrain.crs) ax1.add_image(stamen_terrain, 11) ax1.set_extent([x0+0.1, x1-0.1, y1-(y0-y1), y0+(y0-y1)]) ax1.plot([x0,x1],[y0,y1],'k--',linewidth=0.5,transform=ccrs.Geodetic()) ax1.gridlines(draw_labels=True) if palette=='backwards': pal = sns.color_palette(palette=colours,n_colors=np.size(BOXESX,0)).as_hex()[::-1] else: pal = sns.color_palette(palette=colours,n_colors=np.size(BOXESX,0)).as_hex() for i in range(len(lats)-1): ax1.plot(BOXESX[i,:],BOXESY[i,:],c=pal[i],linewidth=3,transform=ccrs.Geodetic()) ax1.text(lons[i]+0.5*(lons[i+1]-lons[i]),lats[i]+0.5*(lats[i+1]-lats[i]),'%i' % i, transform=ccrs.Geodetic(),horizontalalignment='center',verticalalignment='center') return ax1
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 plotFootprintH3(sat, h3_cells): angle = calcCapAngle(sat.elevation.km, 35) # cells = get_cell_ids_h3(sat.latitude.degrees, sat.longitude.degrees, angle) # print(len(list(cells))) proj = cimgt.Stamen('terrain-background') plt.figure(figsize=(6,6), dpi=400) ax = plt.axes(projection=proj.crs) ax.add_image(proj, 6) # ax.coastlines() ax.set_extent([sat.longitude.degrees-10., sat.longitude.degrees+10., sat.latitude.degrees-10, sat.latitude.degrees+10.], crs=ccrs.Geodetic()) ax.background_patch.set_visible(False) geoms = [] for cellid in h3_cells: # new_cell = s2sphere.Cell(cellid) vertices = [] bounds = h3.h3_to_geo_boundary(cellid) # arrays of [lat, lng] coords = [[lng, lat] for [lat,lng] in bounds] geo = Polygon(coords) geoms.append(geo) ax.add_geometries(geoms, crs=ccrs.Geodetic(), facecolor='red', edgecolor='black', alpha=0.4) ax.plot(sat.longitude.degrees, sat.latitude.degrees, marker='o', color='red', markersize=4, alpha=0.7, transform=ccrs.Geodetic()) plt.savefig('test_h3.png')
def plotFootprint(sat): angle = calcCapAngle(sat.elevation.km, 35) cells = get_cell_ids(sat.latitude.degrees, sat.longitude.degrees, angle) print(len(cells)) proj = cimgt.Stamen('terrain-background') plt.figure(figsize=(6,6), dpi=400) ax = plt.axes(projection=proj.crs) ax.add_image(proj, 6) # ax.coastlines() ax.set_extent([sat.longitude.degrees-10., sat.longitude.degrees+10., sat.latitude.degrees-10, sat.latitude.degrees+10.], crs=ccrs.Geodetic()) ax.background_patch.set_visible(False) geoms = [] for cellid in cells: new_cell = s2sphere.Cell(cellid) vertices = [] for i in range(0, 4): vertex = new_cell.get_vertex(i) latlng = s2sphere.LatLng.from_point(vertex) vertices.append((latlng.lng().degrees, latlng.lat().degrees)) geo = Polygon(vertices) geoms.append(geo) ax.add_geometries(geoms, crs=ccrs.Geodetic(), facecolor='red', edgecolor='black', alpha=0.4) ax.plot(sat.longitude.degrees, sat.latitude.degrees, marker='o', color='red', markersize=4, alpha=0.7, transform=ccrs.Geodetic()) plt.savefig('test.png')
def map_terrain_china(ax=None): """ DESCRIPTION =========== Draws a Stamen terrain map. Takes a cartopy.geoaxes as argument USAGE ===== ax = map_terrain_china(ax) ax: cartopy.GeoAxes retrun ax cartopy.GeoAxes """ if ax==None: ax = plt.gca() stamen_terrain = cimgt.Stamen('terrain-background') ax = map_china(ax) ax.add_image(stamen_terrain, 7) ax.add_feature(cr.feature.RIVERS) ax.add_feature(cr.feature.LAKES) return ax
def plotFootprintH3(lat: float, lon: float, h3_cells: List): """Uses cartopy to replot the footprint, mostly used for debugging and validating math and library usage """ proj = cimgt.Stamen('terrain-background') plt.figure(figsize=(6, 6), dpi=400) ax = plt.axes(projection=ccrs.PlateCarree(central_longitude=180)) ax.add_image(proj, 6) ax.set_extent([lon - 10., lon + 10., lat - 10, lat + 10.], crs=ccrs.Geodetic()) ax.background_patch.set_visible(False) geoms = [] for cellid in h3_cells: vertices = [] bounds = h3.h3_to_geo_boundary(cellid) # arrays of [lat, lng] coords = [[lng, lat] for [lat, lng] in bounds] geo = Polygon(coords) geoms.append(geo) ax.add_geometries(geoms, crs=ccrs.Geodetic(), facecolor='red', edgecolor='black', alpha=0.4) ax.plot(lon, lat, marker='o', color='red', markersize=4, alpha=0.7, transform=ccrs.Geodetic()) plt.savefig('test_h3.png')
def get_background_map(ax, extent): """ Get the background map based on the width of extent in degrees. Args: ax (cartopy.mpl.geoaxes.GeoAxes): DESCRIPTION. extent (list): DESCRIPTION. Returns: ax (TYPE): DESCRIPTION. """ gray_color_RGB = np.array((0.75, 0.75, 0.75)) extent_width = np.abs(extent[1] - extent[0]) if extent_width > 2: # one degree ~ 111 km land_10m = cfeature.NaturalEarthFeature('physical', 'land', '10m', edgecolor='face', facecolor=gray_color_RGB) ax.add_feature(land_10m) ax.add_feature(cfeature.OCEAN, color='white') else: stamen_terrain = cimgt.Stamen('toner-background') stamen_terrain.desired_tile_form = 'L' # tile - color limist RGB [0, 256] # 0 - 5 water - white # 5 - 64 land - white gray boundaries_RGB_tiles = [0, 5, 64] norm = mcolors.BoundaryNorm(boundaries=boundaries_RGB_tiles, ncolors=64) ax.add_image(stamen_terrain, 11, cmap='gray_r', norm=norm) return ax
def plot_map(geometry, events): """ Plot map. :param geometry: :param events: """ stamen_terrain = img_tiles.Stamen('terrain-background') fig = plt.figure() ax = fig.add_subplot(1, 1, 1, projection=stamen_terrain.crs) ax.add_image(stamen_terrain, 10) if events: eq = [] for event in events: eq.append([event.longitude, event.latitude]) eq = np.array(eq).T ax.scatter(eq[0], eq[1], label='Event', transform=ccrs.PlateCarree(), color='#555555', edgecolors='k', linewidth=0.3, marker='o', s=10) if geometry: geom = [] network = geometry[0].network for station in geometry: geom.append([station.longitude, station.latitude]) geom = np.array(geom).T ax.scatter(geom[0], geom[1], label=network, transform=ccrs.PlateCarree(), color='#c72c2c', edgecolors='k', linewidth=0.1, marker='v', s=40) xmin, xmax = ax.get_xlim() ymin, ymax = ax.get_ylim() conv = ProjectionConverter(stamen_terrain.crs, ccrs.PlateCarree()) xmin, ymin = conv.convert(xmin, ymin) xmax, ymax = conv.convert(xmax, ymax) xticks = ticker.LongitudeLocator(nbins=2)._raw_ticks(xmin, xmax) yticks = ticker.LatitudeLocator(nbins=3)._raw_ticks(ymin, ymax) ax.set_xticks(xticks, crs=ccrs.PlateCarree()) ax.set_yticks(yticks, crs=ccrs.PlateCarree()) ax.xaxis.set_major_formatter( ticker.LongitudeFormatter(zero_direction_label=True)) ax.yaxis.set_major_formatter(ticker.LatitudeFormatter()) ax.legend() plt.show()
def map_defining(self, parent=None, width=2, height=1.5, dpi=100): print("PRINT 2: ") self.mapper = Cartopy_Britain_OOP.MapAssembler(self.mapper_input) stamen_terrain = cimgt.Stamen('terrain-background') self.fig = plt.figure(figsize=(4, 5)) self.ax = self.fig.add_subplot(1, 1, 1, projection=stamen_terrain.crs) self.ax.set_extent([2.3, -11.5, 49.2, 60], crs=ccrs.Geodetic()) self.ax.add_image(stamen_terrain, 6) self.map_handling(self.mapper.latlons_done, self.mapper.Ratings_done) FigureCanvas.__init__(self, self.fig) self.setParent(parent)
def plot_monthly_mean(paths, fname): months = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ] fig, axes = plt.subplots(nrows=3, ncols=4, subplot_kw={'projection': ccrs.PlateCarree()}, figsize=(16, 14)) fig.suptitle('Montly averaged Emission Sensitivity {}'.format(fname)) df = pd.read_csv('african_mountains.csv') for ax, path, month in zip(axes.flatten(), paths, months): ds = xr.open_dataset(path) with xr.set_options(keep_attrs=True): ds_monthly_mean = ds.sum(dim='btime').mean(dim='time') ds.close() ds = ds_monthly_mean ds_plot = xr.where(ds.spec001_mr > 0.1, ds.spec001_mr, np.nan) stamen_terrain = cimgt.Stamen('terrain-background') cmap = _gen_flexpart_colormap() ax.add_image(stamen_terrain, 7) im = xr.plot.pcolormesh(ds_plot, norm=colors.LogNorm(0.1, 1e3), cmap=cmap, extend='max', add_colorbar=False, ax=ax) ax.coastlines() ax.add_feature(cr.feature.BORDERS, color='gray') ax.add_feature(cr.feature.RIVERS) ax.add_feature(cr.feature.LAKES) ax.scatter(ds_monthly_mean.RELLNG1, ds_monthly_mean.RELLAT1, marker='*', s=40, transform=ccrs.PlateCarree(), color='black') gl = ax.gridlines(transform=ccrs.PlateCarree(), draw_labels=True, linestyle='--') ax.scatter(df['lon'], df['lat'], color='red', s=2.8) gl.top_labels = False gl.right_labels = False gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER ax.set_extent((22.950000000000003, 45.0, -8.70, 15.75)) ax.set_title(month) cbar_ax = fig.add_axes([0.92, 0.15, 0.05, 0.7]) fig.colorbar(im, cax=cbar_ax, label='Sensitivity to emissions [S]') plt.savefig('figs/{}.png'.format(fname), dpi=300, bbox_inches='tight')
def add_basemap(basemap, ax, crs, zoom=8): if basemap != 'naturalearth': # log.error(f"{basemap}") ax.add_image(img_tiles.Stamen(basemap), zoom) else: z = 110 if zoom > 5: z = 50 if zoom >= 9: z = 10 # print(f"================{zoom} {z}") add_features(ax, get_cfeatures(z)) add_grid(ax, crs)
def make_cartopy(self, projection, ax=None, figsize=(10, 10)): self.projection = projection if ax is None: # Create figure instance fig, ax = plt.subplots(figsize=figsize, subplot_kw=dict(projection=projection)) Lat_1 = self.mapcorners[1] Lat_2 = self.mapcorners[3] Lon_1 = self.mapcorners[0] Lon_2 = self.mapcorners[2] xlocs_1 = ((round(Lon_1 / 10)) - 1) * 10 xlocs_2 = ((round(Lon_2 / 10)) + 1) * 10 ylocs_1 = ((round(Lat_1 / 10)) - 1) * 10 ylocs_2 = ((round(Lat_2 / 10)) + 1) * 10 extent = [Lon_1, Lon_2, Lat_1, Lat_2] x_space = self.latlon_spacing[0] y_space = self.latlon_spacing[1] xlocs = np.arange(xlocs_1, xlocs_2, x_space) ylocs = np.arange(ylocs_1, ylocs_2, y_space) import cartopy.io.img_tiles as cimgt if self.bg_service == 'Stamen': request = cimgt.Stamen(style=self.bg_style) ax.set_extent(extent, crs=self.projection) ax.add_image(request, self.xsize, interpolation='spline36') if self.bg_service == 'OSM': request = cimgt.OSM() ax.set_extent(extent, crs=self.projection) ax.add_image(request, self.xsize, interpolation='spline36') if self.bg_service == 'Google': request = cimgt.GoogleTiles(style=self.bg_style) ax.set_extent(extent) ax.add_image(request, self.xsize, interpolation='spline36') if self.bg_service == 'Esri': request = cimgt.Esri(style=self.bg_style) ax.set_extent(extent, crs=self.projection) ax.add_image(request, self.xsize, interpolation='spline36') gl = ax.gridlines(draw_labels=self.draw_labels, xlocs=xlocs, ylocs=ylocs, alpha=self.alpha_gl) gl.ylabels_left = self.ylabels_left gl.ylabels_right = self.ylabels_right gl.xlabels_top = self.xlabels_top gl.xlabels_bottom = self.xlabels_bottom gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER gl.xlabel_style = self.xlabel_style gl.ylabel_style = self.ylabel_style return ax
def _make_basemap(config, maxdist): g = Geod(ellps='WGS84') hypo = config.hypo maxdiagonal = maxdist * (2**0.5) * 1.10 lonmax, latmax, _ = g.fwd(hypo.longitude, hypo.latitude, 45, maxdiagonal * 1000.) lonmin = 2 * hypo.longitude - lonmax latmin = 2 * hypo.latitude - latmax tile_dir = 'maptiles' stamen_terrain = CachedTiler(cimgt.Stamen('terrain-background'), tile_dir) # Create a GeoAxes figsize = (10, 10) fig = plt.figure(figsize=figsize) ax = fig.add_subplot(111, projection=stamen_terrain.crs) # Add event information as a title textstr = 'evid: {} \nlon: {:.3f} lat: {:.3f} depth: {:.1f} km' textstr = textstr.format(hypo.evid, hypo.longitude, hypo.latitude, hypo.depth) try: textstr += ' time: {}'.format( hypo.origin_time.format_iris_web_service()) except AttributeError: pass ax.text(0., 1.15, textstr, fontsize=10, ha='left', va='top', linespacing=1.5, transform=ax.transAxes) trans = ccrs.Geodetic() ax.set_extent([lonmin, lonmax, latmin, latmax], crs=trans) if config.plot_map_tiles_zoom_level: tile_zoom_level = config.plot_map_tiles_zoom_level else: if maxdiagonal <= 100: tile_zoom_level = 12 else: tile_zoom_level = 8 ax.add_image(stamen_terrain, tile_zoom_level) ax.gridlines(draw_labels=True, color='#777777', linestyle='--') countries = cfeature.NaturalEarthFeature(category='cultural', name='admin_0_countries', scale='10m', facecolor='none') ax.add_feature(countries, edgecolor='k') circle_texts = _plot_circles(ax, hypo.longitude, hypo.latitude, maxdist, 5) return ax, circle_texts
def outlier_station_plot(center, lat_lon_class, factor=8, fpath="plots/outlier_plot.png"): delta = 0.75 square_lons = [77.20 - delta, 77.20 - delta, 77.20 + delta, 77.20 + delta] square_lats = [28.6 - delta, 28.6 + delta, 28.6 + delta, 28.6 - delta] stamen_terrain = cimgt.Stamen('terrain-background') fig = plt.figure(figsize=(8, 8)) ax = fig.add_subplot(projection=stamen_terrain.crs) ax.set_extent([ 77.20 + factor * delta, 77.20 - factor * delta, 28.6 - factor * delta, 28.6 + factor * delta ], ccrs.PlateCarree()) ax.add_image(stamen_terrain, 8) ax.plot(center[1], center[0], marker='o', color='k', markersize=6, alpha=0.7, transform=ccrs.Geodetic()) ring = LinearRing(list(zip(square_lons, square_lats))) ax.add_geometries([ring], ccrs.PlateCarree(), facecolor='none', edgecolor='black') for i in range(len(lat_lon_class)): if lat_lon_class[i][2] == 1: color = "r" elif lat_lon_class[i][2] == 0: color = "g" elif lat_lon_class[i][2] == -1: color = "grey" ax.plot(lat_lon_class[i][1], lat_lon_class[i][0], marker='o', color=color, markersize=4, alpha=0.7, transform=ccrs.Geodetic()) ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True) plt.savefig(fpath)
def plot_map(raster, file_field=None, ceamaxval=None, logcolor=True): plt.figure(figsize=get_map_figure_size(raster.bounds)) ax, mapimg = raster.plotmap( # ax=ax, cmap='jet', logcolor=logcolor, legend=True, # maptype='minimal', grid=True, gridrange=1, vmax=ceamaxval) ax.add_image(cimgt.Stamen('toner-lite'), get_zoomlevel(raster.geobounds)) if file_field is not None: write_to_file_field(file_field, plt.savefig, 'png') plt.clf() plt.close()
def plot_vlba( out_path, ant_lon, ant_lat, base_lon, base_lat, center_lon=-110, center_lat=27.75 ): extent = [-155, -65, 10, 45.5] central_lon = np.mean(extent[:2]) central_lat = np.mean(extent[2:]) stamen_terrain = cimgt.Stamen("terrain-background") plt.figure(figsize=(5.78 * 2, 3.57)) ax = plt.axes(projection=ccrs.Orthographic(central_lon, central_lat)) ax.set_extent(extent) ax.plot( ant_lon, ant_lat, marker=".", color="black", linestyle="none", markersize=6, zorder=10, transform=ccrs.Geodetic(), label="Antenna positions", ) ax.plot( base_lon, base_lat, zorder=5, linestyle="-", linewidth=0.5, alpha=0.7, color="#d62728", label="Baselines", ) ax.add_image(stamen_terrain, 4) leg = plt.legend(markerscale=1.5, fontsize=7, loc=2) for legobj in leg.legendHandles: legobj.set_linewidth(1.5) plt.savefig(out_path, dpi=100, bbox_inches="tight", pad_inches=0.05)
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 main(): # Create a Stamen terrain background instance. stamen_terrain = cimgt.Stamen('terrain-background') fig = plt.figure() # Create a GeoAxes in the tile's projection. ax = fig.add_subplot(1, 1, 1, projection=stamen_terrain.crs) # Limit the extent of the map to a small longitude/latitude range. ax.set_extent([-22, -15, 63, 65], crs=ccrs.Geodetic()) # Add the Stamen data at zoom level 8. ax.add_image(stamen_terrain, 8) # Add a marker for the Eyjafjallajökull volcano. ax.plot(-19.613333, 63.62, marker='o', color='red', markersize=12, alpha=0.7, transform=ccrs.Geodetic()) # Use the cartopy interface to create a matplotlib transform object # for the Geodetic coordinate system. We will use this along with # matplotlib's offset_copy function to define a coordinate system which # translates the text by 25 pixels to the left. geodetic_transform = ccrs.Geodetic()._as_mpl_transform(ax) text_transform = offset_copy(geodetic_transform, units='dots', x=-25) # Add text 25 pixels to the left of the volcano. ax.text(-19.613333, 63.62, u'Eyjafjallajökull', verticalalignment='center', horizontalalignment='right', transform=text_transform, bbox=dict(facecolor='sandybrown', alpha=0.5, boxstyle='round')) plt.show()
def plot_map(longitude_lim, latitude_lim, map_quality=11): """ Plot map. Parameters ---------- longitude_lim : list(2) latitude_lim : list(2) map_quality : int Map rendering quality. 6 is very bad, 10 is ok, 12 is good, 13 is very good, 14 excellent. """ # Map extent eps = 0*0.01 extent = [longitude_lim[0] - eps, longitude_lim[1] + eps, latitude_lim[0] - eps, latitude_lim[1] + eps] # Plot map of Stockholm map_design = 'StamenTerrain' if map_design == 'GoogleTiles': request = cimgt.GoogleTiles() elif map_design == 'QuadtreeTiles': request = cimgt.QuadtreeTiles() elif map_design == 'StamenTerrain': request = cimgt.Stamen('terrain-background') else: # Map designs 'OSM' and 'MapboxTiles' do not work raise Exception('Untested map design') ax = plt.axes(projection=request.crs) gl = ax.gridlines(draw_labels=True, alpha=0., linewidth=0, linestyle='-') gl.top_labels = False gl.right_labels = False gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER gl.xlabel_style = {'size': 10, 'color': 'black'} gl.ylabel_style = {'size': 10, 'color': 'black', 'weight': 'normal'} ax.set_extent(extent) ax.add_image(request, map_quality)
def setup_fig(): sns.set(font_scale=1.6) stamen_terrain = cimgt.Stamen('terrain') fig = plt.figure(figsize=[10, 8]) # setup fig ax = fig.add_subplot(1, 1, 1, projection=stamen_terrain.crs) ax.add_image(stamen_terrain, 15) ax.set_extent([-66.025, -66.057, 18.025, 18.075], ccrs.Geodetic()) # left right down up fig.subplots_adjust(top=0.950, bottom=0, left=0, right=1, hspace=0.27, wspace=0.02) ax.background_patch.set_visible(False) ax.outline_patch.set_visible(False) ax.coastlines(resolution='50m', color='black', zorder=3) ax.stock_img() ax.set_title('Mulas Puerto Rico System [Rough Draft]') return fig, ax
def render_map(): stamen_terrain = cimgt.Stamen("terrain-background") fig = plt.figure() ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree()) ax.set_extent(EXTENT, crs=ccrs.PlateCarree()) ax.add_image(stamen_terrain, 4) # ax.stock_img() ax.coastlines(resolution="50m") ax.add_feature(cfeature.BORDERS) ax.add_feature(cfeature.OCEAN) plt.subplots_adjust(left=0.0, right=1.0, bottom=0.0, top=1.0) fig.set_size_inches(19.2, 10) shpfilename = shpreader.natural_earth(resolution="110m", category="cultural", name="admin_0_countries") reader = shpreader.Reader(shpfilename) country_list = list(reader.records()) for country in country_list: if country.attributes["CONTINENT"] == "Europe": countries.append(country) shpfilename = shpreader.natural_earth(resolution="10m", category="physical", name="lakes") reader = shpreader.Reader(shpfilename) for lake in reader.records(): blocked_areas.append(lake.geometry) ax.add_geometries(lake.geometry, ccrs.PlateCarree()) print(len(blocked_areas)) plt.draw() return fig.canvas.tostring_rgb()
def plotFootprint(lat: float, lon: float, cells: List): """Uses cartopy to replot the footprint, mostly used for debugging and validating math and library usage""" proj = cimgt.Stamen('terrain-background') plt.figure(figsize=(6, 6), dpi=400) ax = plt.axes(projection=proj.crs) ax.add_image(proj, 6) ax.set_extent([lon - 10., lon + 10., lat - 10, lat + 10.], crs=ccrs.Geodetic()) ax.background_patch.set_visible(False) geoms = [] for cellid in cells: new_cell = s2sphere.Cell(cellid) vertices = [] for i in range(0, 4): vertex = new_cell.get_vertex(i) latlng = s2sphere.LatLng.from_point(vertex) vertices.append((latlng.lng().degrees, latlng.lat().degrees)) geo = Polygon(vertices) geoms.append(geo) ax.add_geometries(geoms, crs=ccrs.Geodetic(), facecolor='red', edgecolor='black', alpha=0.4) ax.plot(lon, lat, marker='o', color='red', markersize=4, alpha=0.7, transform=ccrs.Geodetic()) plt.savefig('test.png')
def create_map(coordlist): plt.rcParams["figure.facecolor"] = 'whitesmoke' global fig, ax fig = plt.figure(figsize=(11, 6.5)) # WxH 1100x650 resol = '50m' mapstyle = input('Use stamen terrain? (Y/N): ') if mapstyle == 'Y' or mapstyle == 'y': stamen_terrain = cimgt.Stamen('terrain-background') ax = plt.axes(projection=stamen_terrain.crs) ax.add_image(stamen_terrain, 7) #zoom level else: ax = plt.axes(projection=ccrs.PlateCarree(central_longitude=180)) land = cfeature.NaturalEarthFeature('physical', 'land', scale=resol, edgecolor='darkgreen', facecolor=cfeature.COLORS['land']) ax.add_feature(land, facecolor='olivedrab', edgecolor='darkgreen', zorder=1, alpha=0.8) ax.set_extent(coordlist, ccrs.PlateCarree()) ax.autoscale(False) #coord_lons = np.linspace(coordlist[0], coordlist[1], 5) #coord_lats = np.linspace(coordlist[2], coordlist[3], 5) #lons, lats = np.meshgrid(coord_lons, coord_lats) ocean = cfeature.NaturalEarthFeature('physical', 'ocean', \ scale=resol, edgecolor='none', facecolor='powderblue') lakes = cfeature.NaturalEarthFeature('physical', 'lakes', \ scale=resol, edgecolor=cfeature.COLORS['water'], facecolor=cfeature.COLORS['water']) rivers = cfeature.NaturalEarthFeature('physical', 'rivers_lake_centerlines', \ scale=resol, edgecolor=cfeature.COLORS['water'], facecolor='none') ax.add_feature(ocean) ax.add_feature(lakes) ax.add_feature(rivers, lw=0.5) ax.add_feature(cfeature.BORDERS, color='darkgreen', lw=0.8) ax.add_feature(cfeature.COASTLINE, color='darkgreen', lw=0.5)
def plot_cartopy_rast (proj, C, spc, figtitle, amsx, amsy, amsname, outfile, aspect): ''' Funkcia na vykreslovanie rastra xarray, CONTOURS Parametre: C - xarray s mriezkou a hodnotami na zobrazenie v stlpci 'col' unit - string s jednotkami figtitle - nazov mapy ktory chceme zobrazit ams - tuple alebo list s x a y suradnicou stanice ktoru chceme zobrazit amsname - string s nazvom stanice ktory chceme zobrazit outfile - cesta k vyslednemu obrazku aspect - pomer vysky a sirky domeny ''' #cmap = 'CMRmap_r' cmap = 'cubehelix_r' plt.rcParams.update({'font.size': 16}) plt.rcParams.update({'xtick.labelsize': 16}) plt.rcParams.update({'ytick.labelsize': 16}) plt.rcParams['figure.figsize'] = 15, 15*aspect mapsource = cimgt.Stamen(style='terrain') extent = get_lalo_extent_from_xarray(C) ax = plt.axes(projection=proj) ax.set_extent(extent) ax.add_image(mapsource, 13, interpolation='bilinear') a = C.plot.pcolormesh( alpha = 0.5, cmap=cmap,linewidth=0, antialiased=True,add_colorbar=False) # a = c.plot( levels=levely[spc], alpha=0.5, cmap=cmap, add_colorbar=False) cb = plt.colorbar(a,label=unit_string(spc), orientation="vertical", shrink=0.62) ax.set_title(figtitle, fontdict={'fontsize': '20', 'fontweight' : '4'}) plt.plot(amsx, amsy,'o', markerfacecolor='red', markeredgecolor='black') plt.text(amsx-400, amsy+150 , amsname, color='black', fontsize=12) plt.tight_layout() plt.savefig(outfile, dpi=300, bbox_inches='tight')
import os import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as patches import cartopy.crs as ccrs import cartopy.io.img_tiles as cimgt from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter from seisnn.data.io import read_hyp, read_event_list from seisnn.utils import get_config W, E, S, N = 119, 123, 21.5, 25.7 stamen_terrain = cimgt.Stamen('terrain-background') fig = plt.figure(figsize=(8, 10)) ax = fig.add_subplot(1, 1, 1, projection=stamen_terrain.crs) ax.set_extent([W, E, S, N], crs=ccrs.Geodetic()) ax.add_image(stamen_terrain, 11) events = read_event_list('HL201718') HL_eq = [] for event in events: HL_eq.append([event.origins[0].longitude, event.origins[0].latitude]) HL_eq = np.array(HL_eq).T ax.scatter(HL_eq[0], HL_eq[1], label='Earthquake', transform=ccrs.Geodetic(), color='#333333', edgecolors='k', linewidth=0.3,
for source, i in zip(['Model', 'Monitor', 'DEQ'], [1, 2, 3]): #fig, ax = plt.subplots(3, 1, subplot_kw=dict(projection=projection)) #ax = fig.add_subplot(3,1,i) ax = plt.subplot(3, 1, i, projection=useproj) print('Projection below is ' + str(projection)) lon1 = -125 lon2 = -110.5 lat1 = 41 lat2 = 50 ax.set_extent([lon1, lon2, lat1, lat2], useproj) # Create a Stamen terrain background instance. stamen_terrain = cimgt.Stamen(style='terrain') ax.add_image(stamen_terrain, 8) # Matplotlib portion cmap = mpl.cm.Blues max_users = 250 for country in shpreader.Reader(shp_name).records(): d = df_table.copy() name = country.attributes['Pooled Inc'] column = country.attributes['COL'] row = country.attributes['ROW'] #Locate correct value from df_table d = d.loc[d['Pollutant'] == pollutant].loc[ d['Endpoint Group'] == endpoint].loc[ d['Col'] == column].loc[d['Row'] == row].reset_index(
def draw_total_precipitation(prep, map_extent=(107., 112, 23.2, 26.5), back_image='terrain-background', back_image_zoom=8, title="降水量实况图", draw_station=True, station_info='cities', station_size=22, just_contourf=False): """ 该程序用于显示多日的累积降水量分布特征, 2020/6/7按业务要求制作. Args: ax (matplotlib.axes.Axes): the `Axes` instance used for plotting. prep (dictionary): precipitation, dictionary: {'lon': 1D array, 'lat': 1D array, 'data': 2D array} map_extent (tuple, optional): (lonmin, lonmax, latmin, latmax),. Defaults to (107., 112, 23.2, 26.5). back_image (str, opional): the background image name. Default is stamen 'terrain-background', else is arcgis map server 'World_Physical_Map' (max zoom level is 8) back_image_zoom (int, optional): the zoom level for background image. Defaults to 8. draw_station (bool, optional): draw station name. Defaults to True. station_info (str, optional): station information, 'cities' is 260 city names, or province captial shows. station_size (int, optional): station font size. Defaults to 22. title (str, optional): title string. Defaults to "降水量实况图". Example: import pandas as pd from nmc_met_graphics.plot.precipitation import draw_total_precipitation from nmc_met_io.retrieve_micaps_server import get_model_grids # read data times = pd.date_range(start = pd.to_datetime('2020-06-02 08:00'), end = pd.to_datetime('2020-06-07 08:00'), freq='1H') dataset = get_model_grids("CLDAS/RAIN01_TRI_DATA_SOURCE", times.strftime("%y%m%d%H.000")) data = dataset.sum(dim="time") data['data'].values[data['data'].values > 2400.0] = np.nan prep = {'lon': data['lon'].values, 'lat': data['lat'].values, 'data': data['data'].values} # draw the figure draw_total_precipitation(prep); """ # set figure size fig = plt.figure(figsize=(16, 14.5)) # set map projection datacrs = ccrs.PlateCarree() mapcrs = ccrs.LambertConformal( central_longitude=np.mean(map_extent[0:1]), central_latitude=np.mean(map_extent[2:3]), standard_parallels=(30, 60)) ax = plt.axes((0.1, 0.08, 0.85, 0.92), projection=mapcrs) ax.set_extent(map_extent, crs=datacrs) # add map background add_china_map_2cartopy(ax, name='province', edgecolor='k', lw=1) add_china_map_2cartopy(ax, name='river', edgecolor='cyan', lw=1) if back_image == 'terrain-background': stamen_terrain = cimg.Stamen('terrain-background') ax.add_image(stamen_terrain, back_image_zoom) else: image = cimg.GoogleTiles(url="https://server.arcgisonline.com/arcgis/rest/services/World_Physical_Map/MapServer/tile/{z}/{y}/{x}.jpg") ax.add_image(image, back_image_zoom) # set colors and levels clevs = [50, 100, 200, 300, 400, 500, 600] colors = ['#6ab4f1', '#0001f6', '#f405ee', '#ffa900', '#fc6408', '#e80000', '#9a0001'] linewidths = [1, 1, 2, 2, 3, 4, 4] cmap, norm = mpl.colors.from_levels_and_colors(clevs, colors, extend='max') # draw precipitation contour map x, y = np.meshgrid(prep['lon'], prep['lat']) if just_contourf: _ = ax.contourf( x, y, np.squeeze(prep['data']), clevs, norm=norm, cmap=cmap, transform=datacrs, extend='max', alpha=0.5) else: _ = ax.contourf( x, y, np.squeeze(prep['data']), clevs, norm=norm, cmap=cmap, transform=datacrs, extend='max', alpha=0.1) con2 = ax.contour( x, y, np.squeeze(prep['data']), clevs, norm=norm, cmap=cmap, transform=datacrs, linewidths=linewidths) # add path effects plt.setp(con2.collections, path_effects=[ path_effects.SimpleLineShadow(), path_effects.Normal()]) # add title and legend font = FontProperties(family='Microsoft YaHei', size=32) ax.set_title('降水量实况图(累计降水: 6月02日—6月06日)', loc='center', fontproperties=font) font = FontProperties(family='Microsoft YaHei', size=16) plt.legend([mpatches.Patch(color=b) for b in colors],[ '50~100 毫米', '100~200 毫米', '200-300 毫米', '300~400 毫米', '400~500 毫米', '500~600 毫米', '>=600毫米'], prop=font) # add city information if draw_station: if station_info == 'cities': cities = pd.read_csv(pkg_resources.resource_filename( 'nmc_met_graphics', "resources/stations/cma_city_station_info.dat"), delimiter=r"\s+") else: cities = pd.read_csv(pkg_resources.resource_filename( 'nmc_met_graphics', "resources/stations/provincial_capital.csv")) font = FontProperties(family='SimHei', size=22, weight='bold') geodetic_transform = ccrs.Geodetic()._as_mpl_transform(ax) for _, row in cities.iterrows(): text_transform = offset_copy(geodetic_transform, units='dots', x=-5) ax.plot(row['lon'], row['lat'], marker='o', color='white', markersize=8, alpha=0.7, transform=datacrs) ax.text(row['lon'], row['lat'], row['city_name'], clip_on=True, verticalalignment='center', horizontalalignment='right', transform=text_transform, fontproperties=font, color='white', path_effects=[ path_effects.Stroke(linewidth=1, foreground='black'),path_effects.Normal()]) return fig
def _make_basemap(config, maxdist): g = Geod(ellps='WGS84') hypo = config.hypo maxdiagonal = maxdist * (2**0.5) * 1.10 lonmax, latmax, _ = g.fwd(hypo.longitude, hypo.latitude, 45, maxdiagonal * 1000.) lonmin = 2 * hypo.longitude - lonmax latmin = 2 * hypo.latitude - latmax tile_dir = 'maptiles' stamen_terrain = CachedTiler(cimgt.Stamen('terrain-background'), tile_dir) # Create a GeoAxes figsize = (7.5, 7.5) fig = plt.figure(figsize=figsize, dpi=200) ax = fig.add_subplot(111, projection=stamen_terrain.crs) # Add event information as a title textstr = 'evid: {} \nlon: {:.3f} lat: {:.3f} depth: {:.1f} km' textstr = textstr.format(hypo.evid, hypo.longitude, hypo.latitude, hypo.depth) try: textstr += ' time: {}'.format( hypo.origin_time.format_iris_web_service()) except AttributeError: pass ax.text(0., 1.15, textstr, fontsize=10, ha='left', va='top', linespacing=1.5, transform=ax.transAxes) trans = ccrs.Geodetic() ax.set_extent([lonmin, lonmax, latmin, latmax], crs=trans) if config.plot_map_tiles_zoom_level: tile_zoom_level = config.plot_map_tiles_zoom_level else: if maxdiagonal <= 100: tile_zoom_level = 12 else: tile_zoom_level = 8 logger.info('Map zoom level autoset to: {}'.format(tile_zoom_level)) # Add the image twice, so that the CachedTiler has time to cache # (avoids white tiles on map) ax.add_image(stamen_terrain, tile_zoom_level) ax.add_image(stamen_terrain, tile_zoom_level) ax.gridlines(draw_labels=True, color='#777777', linestyle='--') # add coastlines from GSHHS res_map = { 'full': 'f', 'high': 'h', 'intermediate': 'i', 'low': 'l', 'crude': 'c' } inv_res_map = {v: k for k, v in res_map.items()} if config.plot_coastline_resolution: coastline_resolution = res_map[config.plot_coastline_resolution] else: if maxdiagonal <= 100: coastline_resolution = 'h' else: coastline_resolution = 'i' logger.info('Coastline resolution autoset to: {}'.format( inv_res_map[coastline_resolution])) shpfile = shpreader.gshhs(coastline_resolution) shp = shpreader.Reader(shpfile) with warnings.catch_warnings(): # silent a warning on: # "Shapefile shape has invalid polygon: no exterior rings found" warnings.simplefilter('ignore') ax.add_geometries(shp.geometries(), ccrs.PlateCarree(), edgecolor='black', facecolor='none') ax.add_feature(cfeature.BORDERS, edgecolor='black', facecolor='none') circle_texts = _plot_circles(ax, hypo.longitude, hypo.latitude, maxdist, 5) _plot_hypo(ax, hypo) return ax, circle_texts
def draw_cumulative_precip_and_rain_days(cu_rain=None, days_rain=None, map_extent=(50, 150, 0, 65), regrid_shape=20, add_china=True, city=True, south_China_sea=True, output_dir=None, Global=False): # set font plt.rcParams['font.sans-serif'] = ['SimHei'] # 步骤一(替换sans-serif字体) plt.rcParams['axes.unicode_minus'] = False # 步骤二(解决坐标轴负数的负号显示问题) # set figure plt.figure(figsize=(16, 9)) # plotcrs = ccrs.AlbersEqualArea(central_latitude=(map_extent[2]+map_extent[3])/2., # central_longitude=(map_extent[0]+map_extent[1])/2., standard_parallels=[30., 60.]) plotcrs = ccrs.PlateCarree() datacrs = ccrs.PlateCarree() ax = plt.axes([0.01, 0.1, .98, .84], projection=plotcrs) ax.set_extent(map_extent, crs=datacrs) #map_extent2=utl.adjust_map_ratio(ax,map_extent=map_extent,datacrs=datacrs) # define return plots plots = {} # draw mean sea level pressure #if(os.path.exists('L:/Temp/mask.npy')): # mask=np.load('L:/Temp/mask.npy') #else: #mask=dk_mask.grid_mask_china(cu_rain['lon'], cu_rain['lat']) #np.save('L:/Temp/mask',mask) # draw -hPa geopotential height if days_rain is not None: x, y = np.meshgrid(days_rain['lon'], days_rain['lat']) clevs_days = np.arange(2, np.nanmax(days_rain.values) + 1) z = gaussian_filter(np.squeeze(days_rain.values), 5) #z=z*mask plots['days_rain'] = ax.contour(x, y, z, clevs_days, colors='black', linewidths=2, transform=datacrs, zorder=3) plt_lbs = plt.clabel(plots['days_rain'], inline=2, fontsize=20, fmt='%.0f', colors='black') clip_days = utl.gy_China_maskout(plots['days_rain'], ax, plt_lbs) if cu_rain is not None: x, y = np.meshgrid(cu_rain['lon'], cu_rain['lat']) z = np.squeeze(cu_rain.values) clevs = [50, 100, 200, 300, 400, 500, 600] colors = [ '#6ab4f1', '#0001f6', '#f405ee', '#ffa900', '#fc6408', '#e80000', '#9a0001' ] linewidths = [1, 1, 2, 2, 3, 4, 4] cmap, norm = mpl.colors.from_levels_and_colors(clevs, colors, extend='max') plots['rain'] = ax.contourf(x, y, z, clevs, norm=norm, cmap=cmap, transform=datacrs, extend='max', alpha=0.1) plots['rain2'] = ax.contour(x, y, z, clevs, norm=norm, cmap=cmap, transform=datacrs, linewidths=linewidths) plt.setp(plots['rain2'].collections, path_effects=[ path_effects.SimpleLineShadow(), path_effects.Normal() ]) # plots['rain'] = ax.contourf(x,y,z, # cmap=cmap, zorder=1,transform=datacrs,alpha=0.5) clip_rain = utl.gy_China_maskout(plots['rain'], ax) clip_rain2 = utl.gy_China_maskout(plots['rain2'], ax) #additional information plt.title('过去' + str(int(days_rain.attrs['rn_ndays'])) + '天降水日数, ' + '过去' + str(int(cu_rain.attrs['cu_ndays'])) + '天累积降水量', loc='left', fontsize=30) ax.add_feature(cfeature.OCEAN) utl.add_china_map_2cartopy_public(ax, name='coastline', edgecolor='gray', lw=0.8, zorder=3, alpha=0.5) if add_china: utl.add_china_map_2cartopy_public(ax, name='province', edgecolor='black', lw=0.5, zorder=3) utl.add_china_map_2cartopy_public(ax, name='nation', edgecolor='black', lw=0.8, zorder=3) utl.add_china_map_2cartopy_public(ax, name='river', edgecolor='#74b9ff', lw=0.8, zorder=3, alpha=0.5) stamen_terrain = cimg.Stamen('terrain-background') ax.add_image(stamen_terrain, 6) # grid lines gl = ax.gridlines(crs=datacrs, linewidth=2, color='gray', alpha=0.5, linestyle='--', zorder=1) gl.xlocator = mpl.ticker.FixedLocator(np.arange(0, 360, 15)) gl.ylocator = mpl.ticker.FixedLocator(np.arange(-90, 90, 15)) #utl.add_cartopy_background(ax,name='RD') ax.add_feature(cfeature.LAND, color='#F5E19F') ax.add_feature(cfeature.OCEAN) l, b, w, h = ax.get_position().bounds #forecast information bax = plt.axes([l, b + h - 0.05, .27, .05], facecolor='#FFFFFFCC') bax.set_yticks([]) bax.set_xticks([]) bax.axis([0, 10, 0, 10]) initTime = pd.to_datetime( str(days_rain.coords['forecast_reference_time'].values)).replace( tzinfo=None).to_pydatetime() fcst_time = initTime + timedelta( hours=days_rain.coords['forecast_period'].values[0]) #发布时间 if (sys.platform[0:3] == 'lin'): locale.setlocale(locale.LC_CTYPE, 'zh_CN.utf8') if (sys.platform[0:3] == 'win'): locale.setlocale(locale.LC_CTYPE, 'chinese') plt.text(1.5, 5.5, '观测截止时间: ' + initTime.strftime("%Y年%m月%d日%H时"), size=15) plt.text(1.5, 0.5, 'www.nmc.cn', size=18) # # add color bar # if(cu_rain is not None): # cax=plt.axes([l,b-0.04,w,.02]) # cb = plt.colorbar(plots['rain2'], cax=cax, orientation='horizontal') # cb.ax.tick_params(labelsize='x-large') # cb.set_label('累积降水量 (mm)',size=20) font = FontProperties(family='Microsoft YaHei', size=16) ax.legend([mpatches.Patch(color=b) for b in colors], [ '50~100 毫米', '100~200 毫米', '200-300 毫米', '300~400 毫米', '400~500 毫米', '500~600 毫米', '>=600毫米' ], prop=font, loc='lower left') # add south China sea if south_China_sea: utl.add_south_China_sea(pos=[l + w - 0.091, b, .1, .2]) small_city = False #if(map_extent2[1]-map_extent2[0] < 25): # small_city=True if city: utl.add_city_on_map(ax, map_extent=map_extent, transform=datacrs, zorder=2, size=13, small_city=small_city) utl.add_logo_extra_in_axes(pos=[l - 0.01, b + h - 0.05, .06, .05], which='nmc', size='Xlarge') # show figure if (output_dir != None): plt.savefig(output_dir + '总降水_' + '观测时间_' + initTime.strftime("%Y年%m月%d日%H时") + '.png', dpi=200, bbox_inches='tight') plt.close() if (output_dir == None): plt.show()