def process_crs(crs): """ Parses cartopy CRS definitions defined in one of a few formats: 1. EPSG codes: Defined as string of the form "EPSG: {code}" or an integer 2. proj.4 string: Defined as string of the form "{proj.4 string}" 3. cartopy.crs.CRS instance 4. None defaults to crs.PlateCaree """ try: import cartopy.crs as ccrs import geoviews as gv # noqa import pyproj except: raise ImportError('Geographic projection support requires GeoViews and cartopy.') if crs is None: return ccrs.PlateCarree() if isinstance(crs, basestring) and crs.lower().startswith('epsg'): try: crs = ccrs.epsg(crs[5:].lstrip().rstrip()) except: raise ValueError("Could not parse EPSG code as CRS, must be of the format 'EPSG: {code}.'") elif isinstance(crs, int): crs = ccrs.epsg(crs) elif isinstance(crs, (basestring, pyproj.Proj)): try: crs = proj_to_cartopy(crs) except: raise ValueError("Could not parse EPSG code as CRS, must be of the format 'proj4: {proj4 string}.'") elif not isinstance(crs, ccrs.CRS): raise ValueError("Projection must be defined as a EPSG code, proj4 string, cartopy CRS or pyproj.Proj.") return crs
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 __init__(self, n=1, m=0): super().__init__(n, m) self.f, self.ax = plt.subplots() self.f.subplots_adjust(left=0, bottom=0.05, right=1, top=1, wspace=None, hspace=None) self.ax = plt.axes(projection=ccrs.epsg(26910), frameon=False) # This is a workaround... frameon=False should work in future versions of cartopy self.ax.outline_patch.set_visible(False) self.left = 485844 self.right = 495513 self.bottom = 5453579 self.top = 5462500 self.ax.set_extent([self.left, self.right, self.bottom, self.top], ccrs.epsg(26910)) self.ax.text(self.right, self.bottom - 400, '@VanBikeShareBot', color=fg_color, size=18, alpha=0.6, horizontalalignment='right')
def plot_global(xx, yy, data, data_projection_code, cmin, cmax, ax, plot_type='pcolormesh', show_colorbar=False, cmap='jet', show_grid_lines=True, show_grid_labels=True, levels=20): if show_grid_lines: gl = ax.gridlines(crs=ccrs.PlateCarree(), linewidth=1, color='black', draw_labels=show_grid_labels, alpha=0.5, linestyle='--') else: gl = [] if data_projection_code == 4326: # lat lon does nneed to be projected data_crs = ccrs.PlateCarree() else: data_crs = ccrs.epsg(data_projection_code) if plot_type == 'pcolormesh': p = ax.pcolormesh(xx, yy, data, transform=data_crs, vmin=cmin, vmax=cmax, cmap=cmap) elif plot_type == 'contourf': p = ax.contourf(xx, yy, data, levels, transform=data_crs, vmin=cmin, vmax=cmax, cmap=cmap) else: raise ValueError( 'plot_type must be either "pcolormesh" or "contourf"') ax.coastlines('110m', linewidth=0.8) ax.add_feature(cfeature.LAND) cbar = [] if show_colorbar: sm = plt.cm.ScalarMappable(cmap=cmap, norm=plt.Normalize(cmin, cmax)) sm._A = [] cbar = plt.colorbar(sm, ax=ax) return p, gl, cbar
def plot_trajectory_points(gdf, title=None): """Plot the individual points of the trajectory paths. "Spider" graph. Can only view one day a time before its too much. Parameters ---------- gdf: geodataframe Reprojected trajectery gdf (in memory) """ # set the crs (web mercator=3857) proj = ccrs.epsg(3857) # plot all of the trajectory points plt = gdf.hvplot.points( geo=True, datashade=True, legend=False, width=1000, height=800, xaxis=None, yaxis=None, tiles="CartoLight", cmap="fire", crs=proj, title=title, shared_axes=False, ) return plt
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 getPNG(name, data, epsg, pth): plt.figure(figsize=(20, 10), frameon=False, dpi=300) box = sgeom.box(minx=-127.8294048826629989, maxx=-59.0561278820333229, miny=5.1830409679864857, maxy=49.9999999955067977) x0, y0, x1, y1 = box.bounds ### Create a list of RGB tuples colors = [(229, 229, 229), (182, 165, 134), (160, 138, 91), (138, 111, 49), (140, 127, 43), (142, 143, 37), (144, 159, 31), (146, 175, 25), (138, 177, 21), (119, 165, 18), (99, 154, 15), (80, 142, 12), (60, 131, 9), (41, 119, 6), (22, 108, 3), (3, 97, 0), (0, 23, 0)] # This example uses the 8-bit RGB ### Create an array or list of positions from 0 to 1. position = [0,0.04,0.08,0.12,0.16,0.20,0.24,0.28,0.32,0.36,0.40,0.44,0.48,0.52,0.56,0.60,1] evi_cmap = make_cmap(colors, position=position, bit=True) # Set output projection if epsg == 4326: ax = plt.axes(projection=ccrs.PlateCarree()) else: ax = plt.axes(projection=ccrs.epsg(epsg)) ax.set_global() # Define the coordinate system that the grid lons and grid lats are on coord = ccrs.PlateCarree() # aka Lat,Long # Plots the data data.plot(ax=ax, transform=coord, add_colorbar=False, vmin=-2000, vmax=10000, add_labels=False, cmap=evi_cmap) ax.set_extent([x0, x1, y0, y1]) ax.background_patch.set_visible(False) ax.outline_patch.set_visible(False) # Put Coastline on figure # ax.coastlines() if not os.path.exists("EVI_png"): os.mkdir("EVI_png") plt.savefig(os.path.join("EVI_png", '{0}.png'.format(name)), bbox_inches='tight', dpi=300, transparent=True)
def plot_raster(ax, tif_path, cmap='viridis', levels=None, colors=None, clip_extent=None): """Plot raster with vectors/labels """ # Open raster ds = rioxarray.open_rasterio(tif_path, mask_and_scale=True) if clip_extent is not None: left, right, bottom, top = clip_extent ds = ds.rio.clip_box( minx=left, miny=bottom, maxx=right, maxy=top, ) # Check raster CRS with rasterio.open(tif_path) as da: crs_code = da.crs.to_epsg() if crs_code == 4326: crs = ccrs.PlateCarree() else: crs = ccrs.epsg(crs_code) # Plot raster if levels is not None and colors is not None: ds.plot(ax=ax, levels=levels, colors=colors, transform=crs) else: ds.plot(ax=ax, cmap=cmap, transform=crs) return ax
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_data(self, feature_name): """ Plots the FeatureType.DATA of eopatch. :param feature_name: name of the eopatch feature :type feature_name: str :return: visualization :rtype: holoview/geoviews/bokeh """ crs = self.eopatch.bbox.crs crs = CRS.POP_WEB if crs is CRS.WGS84 else crs data_da = array_to_dataframe(self.eopatch, (FeatureType.DATA, feature_name), crs=crs) if self.mask: data_da = self.mask_data(data_da) timestamps = self.eopatch.timestamp crs = self.eopatch.bbox.crs if not self.rgb: return data_da.hvplot(x='x', y='y', crs=ccrs.epsg(crs.epsg)) data_rgb = self.eopatch_da_to_rgb(data_da, feature_name, crs) rgb_dict = { timestamp_: self.plot_rgb_one(data_rgb, timestamp_) for timestamp_ in timestamps } return hv.HoloMap(rgb_dict, kdims=['time'])
def __init__(self, p): t0 = t() self.p = p if _cartopy: self.l93 = ccrs.epsg(2154) t1 = t() print(f"\nVizualisation created in {np.round(t1 - t0, 2)} seconds\n")
def heatmap(input_nc_variable, col, brk): start_time = time.time() interp_methord='bicubic'#bilinear # proj = ccrs.epsg(3857) #set projection dpi=200 #image quality bounds=list(brk) cmap =colors.ListedColormap(list(col)) norm = colors.BoundaryNorm(bounds, cmap.N) img_extent = (min(input_nc_variable.lon.values), max(input_nc_variable.lon.values), min(input_nc_variable.lat.values), max(input_nc_variable.lat.values)) os.mkdir(input_nc_variable.name) t=0 for time_ in np.datetime_as_string(input_nc_variable.time.values,unit='h'): # print(time_," ",input_nc_variable.name) fig = plt.figure(frameon=False,dpi=dpi) ax = plt.axes(projection=proj) ax.set_extent(img_extent, ccrs.PlateCarree()) ax.outline_patch.set_visible(False) ax.background_patch.set_visible(False) ax.imshow(input_nc_variable[t,:,:].values,interpolation=interp_methord, origin='lower',alpha=.8, cmap=cmap, norm=norm, extent=img_extent, transform=ccrs.PlateCarree()) #ax.contour(grid1_lon,grid1_lat,grid1,alpha=1, levels=bounds, colors='k', transform=ccrs.PlateCarree(),linewidths=0.05) #ax.contour(cntr,grid1_lon,grid1_lat,grid1, colors='black') #ax.clabel(cntr, inline=True, fontsize=8) fig.savefig(input_nc_variable.name+"/"+time_+'.png',bbox_inches='tight',transparent=True,pad_inches = 0.0) plt.close() convert="convert "+input_nc_variable.name+"/"+time_+'.png '+ input_nc_variable.name+"/"+time_+'_4_bit.png' os.system(convert) os.remove(input_nc_variable.name+"/"+time_+'.png') t=t+1 print(input_nc_variable.name,"Heatmap :",round(time.time() - start_time,2),"Sec")
def test_epsg(self): uk = ccrs.epsg(27700) assert uk.epsg_code == 27700 assert_almost_equal(uk.x_limits, (-118365.7408171, 751581.564796)) assert_almost_equal(uk.y_limits, (-5268.1797977, 1272227.798124)) assert_almost_equal(uk.threshold, 8699.47, decimal=2) self._check_osgb(uk)
def main(): terrain = cimgt.MapboxTiles( 'pk.eyJ1IjoiZWVzYWhlIiwiYSI6ImNqdGFjMTI1ODA1ZGc0NHRmN28wcG5ybnEifQ.ZBSMcdbWkjfjRgDVQLjfnw', 'satellite') mycrs = terrain.crs go = ccrs.Mercator.GOOGLE proj = ccrs.epsg(3857) ax = plt.axes(projection=ccrs.PlateCarree()) deltax = 0.1 deltay = 0.05 ax.set_extent([ 24.8359483 - deltax, 24.835948 + deltax, 60.187860 - deltay, 60.187860 + deltay ], crs=go) #fig_terrain, ax_terrain = plt.subplots(figsize=(10,10), subplot_kw=dict(projection=cartopy.crs.Mercator(), facecolor='#000000')) #ax_terrain.set_extent([60.160964,60.180603,24.818373,24.852362], crs=ccrs.Geodetic()) #ax_terrain.add_image(terrain, 13) #plt.savefig("m.png", transparent=True, bbox_inches='tight', pad_inches=0, frameon=None) ax.add_image(terrain, 11) #ax.coastlines('10m') plt.show()
def get_axes(extent=None, figsize=None, epsg=None): """Get transverse mercator axes (default to Vietnam extent) EPSG:4756 """ if extent is None: # extent = [102.2, 109.5, 8.5, 23.3] # mainland extent extent = [101.8, 118.3, 6.7, 23.6] # include islands if figsize is None: # figsize = (6, 10) # mainland (portrait) figsize = (12, 10) # include islands if epsg is not None: ax_proj = ccrs.epsg(epsg) else: x0, x1, y0, y1 = extent cx = x0 + ((x1 - x0) / 2) cy = y0 + ((y1 - y0) / 2) ax_proj = ccrs.LambertConformal(central_longitude=cx, central_latitude=cy) plt.figure(figsize=figsize, dpi=300) ax = plt.axes([0.025, 0.025, 0.95, 0.95], projection=ax_proj) proj = ccrs.PlateCarree() ax.set_extent(extent, crs=proj) set_ax_bg(ax) return ax
def test_epsg(self): uk = ccrs.epsg(27700) assert uk.epsg_code == 27700 assert uk.x_limits == (-84667.135022467062, 676354.14167904819) assert uk.y_limits == (-2957.1831134535023, 1242951.4397385279) assert uk.threshold == 7610.2127670151531 self._check_osgb(uk)
def plot_raster(self, feature_type, feature_name): """ Makes visualization for raster data (except for FeatureType.DATA) :param feature_type: type of eopatch feature :type feature_type: FeatureType :param feature_name: name of eopatch feature :type feature_name: str :return: visualization :rtype: holoviews/geoviews/bokeh """ crs = self.eopatch.bbox.crs crs = CRS.POP_WEB if crs is CRS.WGS84 else crs data_da = array_to_dataframe(self.eopatch, (feature_type, feature_name), crs=crs) data_min = data_da.values.min() data_max = data_da.values.max() data_levels = len(np.unique(data_da)) data_levels = 11 if data_levels > 11 else data_levels data_da = data_da.where(data_da > 0).fillna(-1) vis = data_da.hvplot(x='x', y='y', crs=ccrs.epsg(crs.epsg)).opts( clim=(data_min, data_max), clipping_colors={'min': 'transparent'}, color_levels=data_levels) return vis
def tester_bg3(): """specify extent, and use caropy.io.img_tiles.GootleTiles""" from plotter import calpost_reader as reader import cartopy.crs as ccrs import cartopy.io.img_tiles as cimgt with open('../data/tseries_ch4_1min_conc_co_fl.dat') as f: dat = reader.Reader(f, slice(60 * 12, 60 * 12 + 10)) # background bext = [-11344200.0, -11338900.0, 3724300.0, 3731100.0] plotter_options = { 'contour_options': { 'alpha': .2 }, 'extent': bext, 'projection': ccrs.epsg(3857), # GoogleMap, we may need license 'customize_once': lambda p: p.ax.add_image(cimgt.GoogleTiles(style='satellite'), 15) } x = dat['x'] * 1000 y = dat['y'] * 1000 p = Plotter(dat['v'], dat['ts'], x=x, y=y, plotter_options=plotter_options) p(outdir / 'test_bg3.png')
def tester_bg1(): """load background tif file and use it""" from plotter import calpost_reader as reader import rasterio import cartopy.crs as ccrs with open('../data/tseries_ch4_1min_conc_co_fl.dat') as f: dat = reader.Reader(f, slice(60 * 12, 60 * 12 + 10)) # background b = rasterio.open(bgfile) bext = [ b.transform[2], b.transform[2] + b.transform[0] * b.width, b.transform[5] + b.transform[4] * b.height, b.transform[5] ] plotter_options = { 'contour_options': { 'alpha': .2 }, 'extent': bext, 'projection': ccrs.epsg(3857), 'customize_once': lambda p: p.ax.imshow(b.read()[:3, :, :].transpose((1, 2, 0)), extent=bext, origin='upper') } x = dat['x'] * 1000 y = dat['y'] * 1000 p = Plotter(dat['v'], dat['ts'], x=x, y=y, plotter_options=plotter_options) p(outdir / 'test_bg1.png')
def tester_bgm_w3(): """wms, specify projection/extent""" from plotter import calpost_reader as reader import cartopy.crs as ccrs with open('../data/tseries_ch4_1min_conc_co_fl.dat') as f: dat = reader.Reader(f, slice(60 * 12, 60 * 12 + 10)) # background plotter_options = { 'contour_options': { 'alpha': .2 }, 'background_manager': BackgroundManager( wms_options={ 'wms': 'https://services.nationalmap.gov/arcgis/services/USGSNAIPImagery/ImageServer/WMSServer', 'layers': '0' }, projection=ccrs.epsg(3857), ), 'customize_once': lambda p: p.ax.gridlines(draw_labels=True), } x = dat['x'] * 1000 y = dat['y'] * 1000 p = Plotter(dat['v'], dat['ts'], x=x, y=y, plotter_options=plotter_options) p(outdir / 'test_bgm_w3.png')
def get_plottables(src, bands=None): """ Get georeferenced image information for plotting using imshow """ import cartopy.crs as ccrs import numpy x0, y0 = src.profile['transform'] * (0, 0) x1, y1 = src.profile['transform'] * (src.profile['width'], src.profile['height']) extent = (x0, x1, y0, y1) if not bands: bands = [ 1, ] data = numpy.array([src.read(i) for i in bands]) # TODO automate this data = numpy.moveaxis(data, 0, -1) # Query online for CRS transform = src.profile['crs'].to_epsg() if transform is 4326: transform = ccrs.PlateCarree() else: transform = ccrs.epsg(transform) return data, transform, extent
def setup_axes(): region = maps.get_provinces_and_states( args['shapefiles']).loc['California'].geometry crs = ccrs.epsg(2163) plt.figure( figsize=maps.figsize_fitting_polygon(region, crs, width=1.63386)) ax = plt.axes(projection=crs) maps.set_extent(ax, region) maps.features.format_page(ax, linewidth_axis_spines=0) maps.features.add_polygons(ax, region, exterior=True, zorder=100, facecolor='white') maps.features.add_polygons(ax, region, outline=True, zorder=99, edgecolor='black', linewidth=0.2) maps.add_roads(ax, args['shapefiles'], linewidth=0.3, edgecolor=matplotlib.colors.to_rgba('snow', 0.5)) maps.add_hills(ax, args['shapefiles']) return ax
def tester_tc4(): """show contour from geotiff with background in different projection""" import rasterio import datetime import cartopy.crs as ccrs import numpy as np r = rasterio.open(tiffile) arr = r.read(1) arr = arr.reshape(1, *arr.shape) # print(arr.shape) ext = [r.transform[2], r.transform[2] + r.transform[0] * r.width, r.transform[5] + r.transform[4] * r.height, r.transform[5]] # background b = rasterio.open(bgfile) bext = [b.transform[2], b.transform[2] + b.transform[0] * b.width, b.transform[5] + b.transform[4] * b.height, b.transform[5]] plotter_options = { 'contour_options': {'alpha': .5}, 'extent': bext, 'projection': ccrs.epsg(3857), 'customize_once': lambda p: p.ax.imshow(b.read()[:3, :, :].transpose((1, 2, 0)), extent=bext, origin='upper')} p = Plotter(arr, tstamps=[datetime.date(2020, 12, 4)], extent=ext, plotter_options=plotter_options) p(outdir / 'test_tc4.png')
def test_epsg(self): uk = ccrs.epsg(27700) assert uk.epsg_code == 27700 assert_almost_equal(uk.x_limits, (-104009.357, 688806.007), decimal=3) assert_almost_equal(uk.y_limits, (-8908.37, 1256558.45), decimal=2) assert_almost_equal(uk.threshold, 7928.15, decimal=2) self._check_osgb(uk)
def get_transformation(crs_in): """Get projection and its units to use in cartopy transforamtions from current crs Returns: ccrs.Projection, str """ try: if CRS.from_user_input(crs_in) == CRS.from_user_input( {'init': 'epsg:3395'}): crs_epsg = ccrs.Mercator() else: crs_epsg = ccrs.epsg(CRS.from_user_input(crs_in).to_epsg()) except ValueError: crs_epsg = ccrs.PlateCarree() except requests.exceptions.ConnectionError: LOGGER.warning( 'No internet connection. Using projection PlateCarree in plot.') crs_epsg = ccrs.PlateCarree() try: units = crs_epsg.proj4_params['units'] except KeyError: units = '°' return crs_epsg, units
def plot_basemap_labels(ax, ax_crs=None, labels=None, label_column=None, label_offset=0, include_zorder=20): """Plot countries and regions background """ if ax_crs is None: proj = ccrs.PlateCarree() else: proj = ccrs.epsg(ax_crs) extent = ax.get_extent() if labels is not None: for label in labels.itertuples(): text = getattr(label, label_column) x = float(label.geometry.centroid.x) y = float(label.geometry.centroid.y) size = 8 if within_extent(x, y, extent): ax.text(x - 10 * label_offset, y - 10 * label_offset, text, alpha=0.7, size=size, horizontalalignment='center', zorder=include_zorder, transform=proj)
def tester_s4(): """show contour from calpost with background in different projection plus annotated points""" from plotter import calpost_reader as reader import rasterio import cartopy.crs as ccrs import geopandas as gpd # source locations df = gpd.read_file(shpfile) df = df.to_crs('EPSG:3857') with open('../data/tseries_ch4_1min_conc_co_fl.dat') as f: dat = reader.Reader(f, slice(60 * 12, 60 * 12 + 10)) # background b = rasterio.open(bgfile) bext = [b.transform[2], b.transform[2] + b.transform[0] * b.width, b.transform[5] + b.transform[4] * b.height, b.transform[5]] plotter_options = { 'contour_options': {'alpha': .5}, 'extent': bext, 'projection': ccrs.epsg(3857), 'customize_once': [ lambda p: p.ax.imshow(b.read()[:3, :, :].transpose((1, 2, 0)), extent=bext, origin='upper'), lambda p: df.plot(ax=p.ax, column='kls', categorical=True, legend=True, zorder=10), lambda p: [p.ax.annotate(_.Site_Label, (_.geometry.x, _.geometry.y)) for _ in df.itertuples() if _.Site_Label in ('F1', 'op3_w1', 'S4')], lambda p: p.ax.gridlines(draw_labels=True), ]} x = dat['x'] * 1000 y = dat['y'] * 1000 p = Plotter(dat['v'], dat['ts'], x=x, y=y, plotter_options=plotter_options) p(outdir / 'test_s4.png')
def tester_bg4(): """specify extent, and use NAIP images with cartopy.io.ogc_clients.WMSRasterSource""" from plotter import calpost_reader as reader import cartopy.crs as ccrs # import cartopy.io.ogc_clients as cogcc with open('../data/tseries_ch4_1min_conc_co_fl.dat') as f: dat = reader.Reader(f, slice(60 * 12, 60 * 12 + 10)) def my_add_naip(p): img = p.ax.add_wms( 'https://services.nationalmap.gov/arcgis/services/USGSNAIPImagery/ImageServer/WMSServer', layers='0') # TODO how can i save this...?, or should I save this? # background bext = [-11344200.0, -11338900.0, 3724300.0, 3731100.0] plotter_options = { 'contour_options': { 'alpha': .2 }, 'extent': bext, 'projection': ccrs.epsg(3857), # 'customize_once': lambda p: p.ax.add_wms( # 'https://services.nationalmap.gov/arcgis/services/USGSNAIPImagery/ImageServer/WMSServer', # layers='0' # ) 'customize_once': my_add_naip, } x = dat['x'] * 1000 y = dat['y'] * 1000 p = Plotter(dat['v'], dat['ts'], x=x, y=y, plotter_options=plotter_options) p(outdir / 'test_bg4.png')
def tester_bgm_b3(): """specify extent/projection and bg image""" from plotter import calpost_reader as reader import cartopy.crs as ccrs with open('../data/tseries_ch4_1min_conc_co_fl.dat') as f: dat = reader.Reader(f, slice(60 * 12, 60 * 12 + 10)) # background plotter_options = { 'contour_options': { 'alpha': .2 }, 'background_manager': BackgroundManager( bgfile=bgfile_lcc, projection=ccrs.epsg(3857), ), 'customize_once': lambda p: p.ax.gridlines(draw_labels=True), } x = dat['x'] * 1000 y = dat['y'] * 1000 p = Plotter(dat['v'], dat['ts'], x=x, y=y, plotter_options=plotter_options) p(outdir / 'test_bgm_b3.png')
def tester_bgm_w2b(): """specify projection/extent, then wms""" from plotter import calpost_reader as reader import cartopy.crs as ccrs with open('../data/tseries_ch4_1min_conc_co_fl.dat') as f: dat = reader.Reader(f, slice(60 * 12, 60 * 12 + 10)) # background plotter_options = { 'contour_options': { 'alpha': .2 }, 'background_manager': BackgroundManager( projection=ccrs.epsg(3857), extent=[-11344200.0, -11338900.0, 3724300.0, 3731100.0]), 'customize_once': [ lambda p: p.ax.add_wms( 'https://services.nationalmap.gov/arcgis/services/USGSNAIPImagery/ImageServer/WMSServer', layers='0'), lambda p: p.ax.gridlines(draw_labels=True), ] } x = dat['x'] * 1000 y = dat['y'] * 1000 p = Plotter(dat['v'], dat['ts'], x=x, y=y, plotter_options=plotter_options) p(outdir / 'test_bgm_w2b.png')
def plot_global(xx,yy, data, data_projection_code, cmin, cmax, ax, plot_type = 'pcolormesh', show_colorbar=False, cmap=None, show_grid_lines = True, show_grid_labels = True, grid_linewidth = 1, custom_background = False, background_name = [], background_resolution = [], levels=20): # assign cmap default if cmap is None: if cmin*cmax<0: cmap = 'RdBu_r' else: cmap = 'viridis' if show_grid_lines : gl = ax.gridlines(crs=ccrs.PlateCarree(), linewidth=1, color='black', draw_labels = show_grid_labels, alpha=0.5, linestyle='--', zorder=102) else: gl = [] if data_projection_code == 4326: # lat lon does nneed to be projected data_crs = ccrs.PlateCarree() else: data_crs =ccrs.epsg(data_projection_code) if custom_background: ax.background_img(name=background_name, resolution=background_resolution) if plot_type == 'pcolormesh': p = ax.pcolormesh(xx, yy, data, transform=data_crs, vmin=cmin, vmax=cmax, cmap=cmap) elif plot_type =='contourf': p = ax.contourf(xx, yy, data, levels, transform=data_crs, vmin=cmin, vmax=cmax, cmap=cmap) else: raise ValueError('plot_type must be either "pcolormesh" or "contourf"') if not custom_background: ax.add_feature(cfeature.LAND, zorder=100) ax.coastlines('110m', linewidth=grid_linewidth, zorder=101) cbar = [] if show_colorbar: sm = plt.cm.ScalarMappable(cmap=cmap, norm=plt.Normalize(cmin,cmax)) sm._A = [] cbar = plt.colorbar(sm,ax=ax) return p, gl, cbar
def test_epsg(self): uk = ccrs.epsg(27700) assert uk.epsg_code == 27700 assert_almost_equal( uk.x_limits, (-118365.7408171, 751581.564796)) assert_almost_equal( uk.y_limits, (-5268.1797977, 1272227.798124)) assert_almost_equal(uk.threshold, 8699.47, decimal=2) self._check_osgb(uk)
def test_epsg(self): uk = ccrs.epsg(27700) self.assertEqual(uk.epsg_code, 27700) self.assertEqual(uk.x_limits, (-83948.465999040171, 675634.89881823619)) self.assertEqual(uk.y_limits, (-2994.0109472532495, 1241785.8617898584)) self.assertEqual(uk.threshold, 7595.8336481727638) self._check_osgb(uk)
def test_epsg(self): uk = ccrs.epsg(27700) self.assertEqual(uk.epsg_code, 27700) self.assertEqual(uk.x_limits, (-84667.135022467002, 676354.14167904831)) self.assertEqual(uk.y_limits, (-2957.1831134549138, 1242951.4397385262 )) self.assertEqual(uk.threshold, 7610.2127670151531) self._check_osgb(uk)
scale='50m', facecolor='none') ax.add_feature(land,facecolor='lightgray', zorder = 1) ax.add_feature(ocean,facecolor='lightblue', zorder = 1) ax.add_feature(states_provinces, edgecolor='black', zorder = 2) #linewidth = 2 ax.add_feature(country_borders, edgecolor='black', zorder = 2) # read shape file #shphru = cartopy.io.shapereader.Reader('D:\\@Workspace\\SUMMA\\shapefiles\\ColumbiaBasin_Proj.shp') shphru = cartopy.io.shapereader.Reader('D:\\@Workspace\\SUMMA\\outputs\\columbia_hru_output.shp') hrus = shphru.records() ihru = 0 for hru in hrus: ax.add_geometries(hru.geometry, crs=ccrs.epsg(5070), facecolor=cmap(lhnew[ihru]), zorder=3) ihru += 1 if ihru > 5000: break #%% import matplotlib.pyplot as plt import matplotlib.cm as mplcm import matplotlib.colors as colors import numpy as np NUM_COLORS = 20 cm = plt.get_cmap('gist_rainbow') cNorm = colors.Normalize(vmin=0, vmax=NUM_COLORS-1)
name = record.attributes['name'].decode('latin-1') if name in states: facecolor = 'DarkOrange' else: facecolor = 'LightGray' ax.add_geometries([state], ccrs.PlateCarree(), facecolor=facecolor, edgecolor='black') # Now for the UK srcdir = os.path.join(os.path.expanduser('~'),'Dropbox','KCL Modules','Undergraduate','2nd Year','Spatial Analysis','SpatialAnalysis') shpdir = os.path.join(srcdir,'shapefiles') outdir = os.path.join(os.path.expanduser('~'),'Desktop') shp = shapereader.Reader(os.path.join(shpdir,'LDN-LSOAs.shp')) subplot_kw = dict(projection=ccrs.epsg(27700)) fig, ax = plt.subplots(figsize=(5, 5), subplot_kw=subplot_kw) ax.set_extent([0, 1000000, 0, 1000000], crs=ccrs.epsg(27700)) ax.background_patch.set_visible(False) ax.outline_patch.set_visible(False) for record, state in zip(shp.records(), shp.geometries()): name = record.attributes['LSOA11CD'].decode('latin-1') if name in states: facecolor = 'DarkOrange' else: facecolor = 'LightGray' ax.add_geometries([state], ccrs.epsg(27700), facecolor=facecolor, edgecolor='black')
crs_proj4 = crs.proj4_init df_ae = df.to_crs(crs_proj4) # Here's what the plot looks like in GeoPandas df_ae.plot() ############################################################################### # Now that our data is in a CRS based off of CartoPy, we can easily # plot it. fig, ax = plt.subplots(subplot_kw={'projection': crs}) ax.add_geometries(df_ae['geometry'], crs=crs) ############################################################################### # Note that we could have easily done this with an EPSG code like so: crs_epsg = ccrs.epsg('3857') df_epsg = df.to_crs(epsg='3857') # Generate a figure with two axes, one for CartoPy, one for GeoPandas fig, axs = plt.subplots(1, 2, subplot_kw={'projection': crs_epsg}, figsize=(10, 5)) # Make the CartoPy plot axs[0].add_geometries(df_epsg['geometry'], crs=crs_epsg, facecolor='white', edgecolor='black') # Make the GeoPandas plot df_epsg.plot(ax=axs[1], color='white', edgecolor='black') ############################################################################### # CartoPy to GeoPandas # ==================== #
def test_epsg_compound_crs(self): projection = ccrs.epsg(5973) assert projection.epsg_code == 5973