def scatterplot_in_map(longitudes: np.array, latitudes: np.array, bounding_box: Tuple[int, int, int, int], bounding_box_context: Tuple[int, int, int, int] = BOUNDS_BALTIC_SEA, projection: ccrs.CRS = ccrs.EuroPP(), coastline: bool = True, stock_img: bool = True, title: str = None, **kwargs): """ The function plots scatterplot within a map in a specific projection (parameter projection) so that the map is limited by bounding_box_context and within those bounds bounding_box is visualized with a solid line box = lon_min, lat_min, lon_max, lat_max Parameters: longitudes (np.array): a Nx1 array containing the longitudes latitudes (np.array): a Nx1 array containing the latitudes bounding_box (Tuple[int,int,int,int]): a Tuple with (longitude min, latitude min, longitude max, latitude max) for the visualized bounding box bounding_box_context (Tuple[int,int,int,int]): a Tuple with (longitude min, latitude min, longitude max, latitude max) for the bounds of the plot projection (ccrs.CRS): Projection used in plotting. defaults to ccrs.EuroPP coastline (bool): If the plot visualizes the coastline stock_img (bool): If the plot visualizes the background title (str): The title of the plot **kwargs: extra parameters to be passed to the matplotlib pyplot scatter-function Returns: matplotlib.figure that contains the region """ plot_region_in_map(bounding_box, bounding_box_context=bounding_box_context, projection=projection, coastline=coastline, stock_img=stock_img, title=title) plt.scatter(longitudes, latitudes, transform=ccrs.PlateCarree(), **kwargs)
def test_europp(self): europp = ccrs.EuroPP() proj4_init = europp.proj4_init # Transverse Mercator, UTM zone 32, assert '+proj=utm' in proj4_init assert '+zone=32' in proj4_init # International 1924 ellipsoid. assert '+ellps=intl' in proj4_init
def plot(self, cube, name): plt.figure(figsize=(8, 6)) proj = ccrs.EuroPP() plt.axes(projection=proj) contour = qplt.contourf(cube) plt.gca().coastlines() plt.clabel(contour, inline=False) plt.savefig( os.path.join('/esarchive/scratch/jcos/esmvaltool/output/figures/', name)) plt.clf()
def pch_eur_(fig, nrow, ncol, n, cube, rg=None, ti=None, pcho={}, fr_on=False): ext = _mapext(rg=rg, cube=cube) proj = ccrs.EuroPP() return pch_(fig, nrow, ncol, n, cube, proj, ext=ext, ti=ti, pcho=pcho, fr_on=fr_on)
def plot_region_in_map(bounding_box: Tuple[int, int, int, int], bounding_box_context: Tuple[int, int, int, int] = BOUNDS_BALTIC_SEA, projection: ccrs.CRS = ccrs.EuroPP(), coastline: bool = True, stock_img: bool = True, title: str = None): """ The function plots a map in a specific projection (parameter projection) so that the map is limited by bounding_box_context and within those bounds bounding_box is visualized with a solid line box = lon_min, lat_min, lon_max, lat_max Parameters: bounding_box (Tuple[int,int,int,int]): a Tuple with (longitude min, latitude min, longitude max, latitude max) for the visualized bounding box bounding_box_context (Tuple[int,int,int,int]): a Tuple with (longitude min, latitude min, longitude max, latitude max) for the bounds of the plot projection (ccrs.CRS): Projection used in plotting. defaults to ccrs.EuroPP coastline (bool): If the plot visualizes the coastline stock_img (bool): If the plot visualizes the background title (str): The title of the plot Returns: matplotlib.figure that contains the region """ fig = plt.figure(figsize=(MAPHEIGHT, MAPWIDTH)) ax = plt.axes(projection=projection) if stock_img: ax.stock_img() if coastline: ax.coastlines(resolution='50m') if bounding_box is not None: lats = np.array([ bounding_box[1], bounding_box[1], bounding_box[3], bounding_box[3], bounding_box[1] ]) lons = np.array([ bounding_box[0], bounding_box[2], bounding_box[2], bounding_box[0], bounding_box[0] ]) plt.plot(lons, lats, transform=ccrs.PlateCarree(), c='k') proj_coords = projection.transform_points( ccrs.PlateCarree(), np.array([bounding_box_context[1], bounding_box_context[3]]), np.array([bounding_box_context[0], bounding_box_context[2]])) ax.set_ylim([proj_coords[0, 1], proj_coords[1, 1]]) ax.set_xlim([proj_coords[0, 0], proj_coords[1, 0]]) ax.gridlines(draw_labels=True) if title is not None: plt.title(title) return fig
def test_europp(self): europp = ccrs.EuroPP() proj4_init = europp.proj4_init # Transverse Mercator, UTM zone 32, self.assertTrue('+proj=tmerc' in proj4_init) self.assertTrue('+zone=32' in proj4_init) # International 1924 ellipsoid. self.assertTrue('+ellps=intl' in proj4_init) # Scale factor on central meridian self.assertTrue('+k=0.9996' in proj4_init) # True origin Standard latitude and longitude self.assertTrue('+lat_0=50' in proj4_init) self.assertTrue('+lon_0=9' in proj4_init) # Map co-ordinates of true origin (metres) self.assertTrue('+x_0=1750000' in proj4_init) self.assertTrue('+y_0=1500000' in proj4_init)
def test_self_intersecting_1(self): # Geometry comes from a matplotlib contourf (see #537) wkt = ('POLYGON ((366.22000122 -9.71489298, ' '366.73212393 -9.679999349999999, ' '366.77412634 -8.767753000000001, ' '366.17762962 -9.679999349999999, ' '366.22000122 -9.71489298), ' '(366.22000122 -9.692636309999999, ' '366.32998657 -9.603356099999999, ' '366.74765799 -9.019999500000001, ' '366.5094086 -9.63175386, ' '366.22000122 -9.692636309999999))') geom = shapely.wkt.loads(wkt) source, target = ccrs.RotatedPole(198.0, 39.25), ccrs.EuroPP() projected = target.project_geometry(geom, source) # Before handling self intersecting interiors, the area would be # approximately 13262233761329. area = projected.area self.assertTrue(2.2e9 < area < 2.3e9, msg='Got area {}, expecting ~2.2e9'.format(area))
use_horizontal_colorbar = False use_mask = False use_gridliner = True cmap = 'coolwarm' fontsize = 14 top_pad = 0.9 projection = 'robinson' if projection == 'platecarree': p = ccrs.PlateCarree(central_longitude=0); threshold = 0 if projection == 'mollweide': p = ccrs.Mollweide(central_longitude=0); threshold = 1e6 if projection == 'robinson': p = ccrs.Robinson(central_longitude=0); threshold = 0 if projection == 'equalearth': p = ccrs.EqualEarth(central_longitude=0); threshold = 0 if projection == 'geostationary': p = ccrs.Geostationary(central_longitude=0); threshold = 0 if projection == 'goodehomolosine': p = ccrs.InterruptedGoodeHomolosine(central_longitude=0); threshold = 0 if projection == 'europp': p = ccrs.EuroPP(); threshold = 0 if projection == 'northpolarstereo': p = ccrs.NorthPolarStereo(); threshold = 0 if projection == 'southpolarstereo': p = ccrs.SouthPolarStereo(); threshold = 0 if projection == 'lambertconformal': p = ccrs.LambertConformal(central_longitude=0); threshold = 0 #---------------------------------------------------------------------------- # DARK BACKGROUND THEME #---------------------------------------------------------------------------- matplotlib.rcParams['text.usetex'] = False rcParams['font.family'] = ['DejaVu Sans'] rcParams['font.sans-serif'] = ['Avant Garde'] plt.rc('text',color='white') plt.rc('lines',color='white') plt.rc('patch',edgecolor='white') plt.rc('grid',color='lightgray')
def kaart(file_path: str, punten: np.ndarray, vector: np.ndarray, perioden: int, terrein: bool = True, sep: str = ",", mu: float = 0, sigma: float = 1, cmap_type: str = "Dark2") -> None: """Maakt een kaart gebaseerd op de coordinaten in een CSV-bestand. :param file_path: Pad naar het te plotten CSV-bestand :param punten: Numpy array van n bij 2. Iedere row bevat een x en y coördinaat. :param vector: Numpy array van n bij 1. Bevat per cell 0 of 1. Iedere cell waar 1 staat, begint de infectie. :param perioden: Het aantal perioden dat de kaart moet berekenen. :param terrein: optioneel, zorgt voor een grafische achtergrond van de plot. Kan enkele seconden langer duren. :param sep: optioneel, seperator van het CSV-bestand :param mu: gemiddelde van de normale verdelingen :param sigma: standaard deviatie van de normale verdelingen :param cmap_type: De te gebruiken colormap voor de plot :returns: Een kaart met de geplotte punten, al dan niet met een 'terrein-achtergrond'. Kleur van de stippen staat voor de periode wanneer zij volledig besmet raakten. """ if not isinstance(file_path, str) or not isinstance(punten, np.ndarray) or not isinstance(vector, np.ndarray) \ or not isinstance(perioden, int) or not isinstance(terrein, bool) or not isinstance(sep, str) or not \ isinstance(mu, (float, int)) or not isinstance(sigma, (float, int)) or not isinstance(cmap_type, str): raise ValueError("Verkeerde waardes meegegeven als argumenten") if punten.shape[0] != vector.shape[0]: raise ValueError("Vector en punten moeten even lang zijn.") print("Kaart aan het maken. \nEven geduld a.u.b, dit kan even duren...") plt.rcParams["figure.figsize"] = [8, 8] # Grotere plots in Jupyter Notebook coordinaten = pd.read_csv(file_path, sep=sep) coordinaten = coordinaten.loc[ (coordinaten["latitude"] < 53.5) & (coordinaten["latitude"] > 50.7) & (coordinaten["longitude"] < 7.3) & (coordinaten["longitude"] > 3.3)] # Filter NL coordinaten = coordinaten.values[:, :] # DataFrame omzetten naar Numpy-array sf_path = "data/shapefiles/gadm36_NLD_2.shp" sf_data = list(shpreader.Reader(sf_path).geometries()) ax = plt.axes(projection=ccrs.EuroPP()) if terrein: ax.add_image(Stamen("terrain-background"), 12) ax.add_geometries(sf_data, ccrs.PlateCarree(), edgecolor="black", facecolor="none", alpha=1) else: ax.add_geometries(sf_data, ccrs.PlateCarree(), edgecolor="black", facecolor="orange", alpha=0.2) ax.set_extent([ min(coordinaten[:, 1]), max(coordinaten[:, 1]), min(coordinaten[:, 0]), max(coordinaten[:, 0]) ]) # Grootte gelijk aan min/max van coordinaten matrix_verloop = bereken.matrix_vec_verloop(punten, vector, perioden, mu=mu, sigma=sigma) perc_voll_inf = bereken.perc_volledige_infectie(matrix_verloop) color_map = cm.get_cmap(cmap_type, 12) for i, coord in enumerate(coordinaten): # Stippen tekenen ax.plot(coord[1], coord[0], marker="o", markersize=3, color=color_map(perc_voll_inf[i]), transform=ccrs.PlateCarree()) for i, punt in enumerate(vector): if punt: ax.plot(punten[i][1], punten[i][0], marker="D", markersize=12, color="red", transform=ccrs.PlateCarree()) plt.show()
def projection(self): if self.proj is None: return ccrs.PlateCarree() proj_dict = ast.literal_eval(self.proj) user_proj = proj_dict.pop("proj") if user_proj == 'PlateCarree': self.xylim_supported = True return ccrs.PlateCarree(**proj_dict) elif user_proj == 'AlbersEqualArea': return ccrs.AlbersEqualArea(**proj_dict) elif user_proj == 'AzimuthalEquidistant': return ccrs.AzimuthalEquidistant(**proj_dict) elif user_proj == 'EquidistantConic': return ccrs.EquidistantConic(**proj_dict) elif user_proj == 'LambertConformal': return ccrs.LambertConformal(**proj_dict) elif user_proj == 'LambertCylindrical': return ccrs.LambertCylindrical(**proj_dict) elif user_proj == 'Mercator': return ccrs.Mercator(**proj_dict) elif user_proj == 'Miller': return ccrs.Miller(**proj_dict) elif user_proj == 'Mollweide': return ccrs.Mollweide(**proj_dict) elif user_proj == 'Orthographic': return ccrs.Orthographic(**proj_dict) elif user_proj == 'Robinson': return ccrs.Robinson(**proj_dict) elif user_proj == 'Sinusoidal': return ccrs.Sinusoidal(**proj_dict) elif user_proj == 'Stereographic': return ccrs.Stereographic(**proj_dict) elif user_proj == 'TransverseMercator': return ccrs.TransverseMercator(**proj_dict) elif user_proj == 'UTM': return ccrs.UTM(**proj_dict) elif user_proj == 'InterruptedGoodeHomolosine': return ccrs.InterruptedGoodeHomolosine(**proj_dict) elif user_proj == 'RotatedPole': return ccrs.RotatedPole(**proj_dict) elif user_proj == 'OSGB': self.xylim_supported = False return ccrs.OSGB(**proj_dict) elif user_proj == 'EuroPP': self.xylim_supported = False return ccrs.EuroPP(**proj_dict) elif user_proj == 'Geostationary': return ccrs.Geostationary(**proj_dict) elif user_proj == 'NearsidePerspective': return ccrs.NearsidePerspective(**proj_dict) elif user_proj == 'EckertI': return ccrs.EckertI(**proj_dict) elif user_proj == 'EckertII': return ccrs.EckertII(**proj_dict) elif user_proj == 'EckertIII': return ccrs.EckertIII(**proj_dict) elif user_proj == 'EckertIV': return ccrs.EckertIV(**proj_dict) elif user_proj == 'EckertV': return ccrs.EckertV(**proj_dict) elif user_proj == 'EckertVI': return ccrs.EckertVI(**proj_dict) elif user_proj == 'EqualEarth': return ccrs.EqualEarth(**proj_dict) elif user_proj == 'Gnomonic': return ccrs.Gnomonic(**proj_dict) elif user_proj == 'LambertAzimuthalEqualArea': return ccrs.LambertAzimuthalEqualArea(**proj_dict) elif user_proj == 'NorthPolarStereo': return ccrs.NorthPolarStereo(**proj_dict) elif user_proj == 'OSNI': return ccrs.OSNI(**proj_dict) elif user_proj == 'SouthPolarStereo': return ccrs.SouthPolarStereo(**proj_dict)
# alpha=0.8, # transform=ccrs.Geodetic()) # ) # ax.gridlines() # ax.coastlines() # plt.show() import cartopy.crs as ccrs import matplotlib.pyplot as plt #ax = plt.axes(projection=ccrs.Mollweide()) ax = plt.axes(projection=ccrs.PlateCarree()) # Good for the USA ax = plt.axes(projection=ccrs.EuroPP()) # Good for the EU ax.coastlines() #ax.stock_img() ax.set_global() # Show the whole globe. def is_polygon_clockwise(coordinate_list): # http://en.wikipedia.org/wiki/Shoelace_formula # https://stackoverflow.com/questions/1165647/how-to-determine-if-a-list-of-polygon-points-are-in-clockwise-order area = 0 last_xy = coordinate_list[-1] for xy in coordinate_list: area += (xy[0] - last_xy[0]) * (xy[1] + last_xy[1]) last_xy = xy return area > 0
def set_proj(projection='Robinson', proj_default=True): """ Set the projection for Cartopy. Parameters ---------- projection : string the map projection. Available projections: 'Robinson' (default), 'PlateCarree', 'AlbertsEqualArea', 'AzimuthalEquidistant','EquidistantConic','LambertConformal', 'LambertCylindrical','Mercator','Miller','Mollweide','Orthographic', 'Sinusoidal','Stereographic','TransverseMercator','UTM', 'InterruptedGoodeHomolosine','RotatedPole','OSGB','EuroPP', 'Geostationary','NearsidePerspective','EckertI','EckertII', 'EckertIII','EckertIV','EckertV','EckertVI','EqualEarth','Gnomonic', 'LambertAzimuthalEqualArea','NorthPolarStereo','OSNI','SouthPolarStereo' proj_default : bool If True, uses the standard projection attributes from Cartopy. Enter new attributes in a dictionary to change them. Lists of attributes can be found in the Cartopy documentation: https://scitools.org.uk/cartopy/docs/latest/crs/projections.html#eckertiv Returns ------- proj : the Cartopy projection object See Also -------- pyleoclim.utils.mapping.map_all : mapping function making use of the projection """ if proj_default is not True and type(proj_default) is not dict: raise TypeError( 'The default for the projections should either be provided' + ' as a dictionary or set to True') # Set the projection if projection == 'Robinson': if proj_default is True: proj = ccrs.Robinson() else: proj = ccrs.Robinson(**proj_default) elif projection == 'PlateCarree': if proj_default is True: proj = ccrs.PlateCarree() else: proj = ccrs.PlateCarree(**proj_default) elif projection == 'AlbersEqualArea': if proj_default is True: proj = ccrs.AlbersEqualArea() else: proj = ccrs.AlbersEqualArea(**proj_default) elif projection == 'AzimuthalEquidistant': if proj_default is True: proj = ccrs.AzimuthalEquidistant() else: proj = ccrs.AzimuthalEquidistant(**proj_default) elif projection == 'EquidistantConic': if proj_default is True: proj = ccrs.EquidistantConic() else: proj = ccrs.EquidistantConic(**proj_default) elif projection == 'LambertConformal': if proj_default is True: proj = ccrs.LambertConformal() else: proj = ccrs.LambertConformal(**proj_default) elif projection == 'LambertCylindrical': if proj_default is True: proj = ccrs.LambertCylindrical() else: proj = ccrs.LambertCylindrical(**proj_default) elif projection == 'Mercator': if proj_default is True: proj = ccrs.Mercator() else: proj = ccrs.Mercator(**proj_default) elif projection == 'Miller': if proj_default is True: proj = ccrs.Miller() else: proj = ccrs.Miller(**proj_default) elif projection == 'Mollweide': if proj_default is True: proj = ccrs.Mollweide() else: proj = ccrs.Mollweide(**proj_default) elif projection == 'Orthographic': if proj_default is True: proj = ccrs.Orthographic() else: proj = ccrs.Orthographic(**proj_default) elif projection == 'Sinusoidal': if proj_default is True: proj = ccrs.Sinusoidal() else: proj = ccrs.Sinusoidal(**proj_default) elif projection == 'Stereographic': if proj_default is True: proj = ccrs.Stereographic() else: proj = ccrs.Stereographic(**proj_default) elif projection == 'TransverseMercator': if proj_default is True: proj = ccrs.TransverseMercator() else: proj = ccrs.TransverseMercator(**proj_default) elif projection == 'TransverseMercator': if proj_default is True: proj = ccrs.TransverseMercator() else: proj = ccrs.TransverseMercator(**proj_default) elif projection == 'UTM': if proj_default is True: proj = ccrs.UTM() else: proj = ccrs.UTM(**proj_default) elif projection == 'UTM': if proj_default is True: proj = ccrs.UTM() else: proj = ccrs.UTM(**proj_default) elif projection == 'InterruptedGoodeHomolosine': if proj_default is True: proj = ccrs.InterruptedGoodeHomolosine() else: proj = ccrs.InterruptedGoodeHomolosine(**proj_default) elif projection == 'RotatedPole': if proj_default is True: proj = ccrs.RotatedPole() else: proj = ccrs.RotatedPole(**proj_default) elif projection == 'OSGB': if proj_default is True: proj = ccrs.OSGB() else: proj = ccrs.OSGB(**proj_default) elif projection == 'EuroPP': if proj_default is True: proj = ccrs.EuroPP() else: proj = ccrs.EuroPP(**proj_default) elif projection == 'Geostationary': if proj_default is True: proj = ccrs.Geostationary() else: proj = ccrs.Geostationary(**proj_default) elif projection == 'NearsidePerspective': if proj_default is True: proj = ccrs.NearsidePerspective() else: proj = ccrs.NearsidePerspective(**proj_default) elif projection == 'EckertI': if proj_default is True: proj = ccrs.EckertI() else: proj = ccrs.EckertI(**proj_default) elif projection == 'EckertII': if proj_default is True: proj = ccrs.EckertII() else: proj = ccrs.EckertII(**proj_default) elif projection == 'EckertIII': if proj_default is True: proj = ccrs.EckertIII() else: proj = ccrs.EckertIII(**proj_default) elif projection == 'EckertIV': if proj_default is True: proj = ccrs.EckertIV() else: proj = ccrs.EckertIV(**proj_default) elif projection == 'EckertV': if proj_default is True: proj = ccrs.EckertV() else: proj = ccrs.EckertV(**proj_default) elif projection == 'EckertVI': if proj_default is True: proj = ccrs.EckertVI() else: proj = ccrs.EckertVI(**proj_default) elif projection == 'EqualEarth': if proj_default is True: proj = ccrs.EqualEarth() else: proj = ccrs.EqualEarth(**proj_default) elif projection == 'Gnomonic': if proj_default is True: proj = ccrs.Gnomonic() else: proj = ccrs.Gnomonic(**proj_default) elif projection == 'LambertAzimuthalEqualArea': if proj_default is True: proj = ccrs.LambertAzimuthalEqualArea() else: proj = ccrs.LambertAzimuthalEqualArea(**proj_default) elif projection == 'NorthPolarStereo': if proj_default is True: proj = ccrs.NorthPolarStereo() else: proj = ccrs.NorthPolarStereo(**proj_default) elif projection == 'OSNI': if proj_default is True: proj = ccrs.OSNI() else: proj = ccrs.OSNI(**proj_default) elif projection == 'OSNI': if proj_default is True: proj = ccrs.SouthPolarStereo() else: proj = ccrs.SouthPolarStereo(**proj_default) else: raise ValueError('Invalid projection type') return proj
def closest_point_of_approach( traffic: "Traffic", lateral_separation: float, vertical_separation: float, projection: Union[pyproj.Proj, crs.Projection, None] = None, round_t: str = "d", max_workers: int = 4, ) -> CPA: """ Computes a CPA dataframe for all pairs of trajectories candidates for being separated by less than lateral_separation in vertical_separation. In order to be computed efficiently, the method needs the following parameters: - projection: a first filtering is applied on the bounding boxes of trajectories, expressed in meters. You need to provide a decent projection able to approximate distances by Euclide formula. By default, EuroPP() projection is considered, but a non explicit argument will raise a warning. - round_t: an additional column will be added in the DataFrame to group trajectories by relevant time frames. Distance computations will be considered only between trajectories flown in the same time frame. By default, the 'd' pandas freq parameter is considered, to group trajectories by day, but other ways of splitting ('h') may be more relevant and impact performance. - max_workers: distance computations are spread over a given number of processors. """ if projection is None: logging.warn("Defaulting to projection EuroPP()") projection = crs.EuroPP() if isinstance(projection, crs.Projection): projection = pyproj.Proj(projection.proj4_init) def yield_pairs(t_chunk: "Traffic"): """ This function yields all pairs of possible candidates for a CPA calculation. """ for first, second in combinations( t_chunk, lateral_separation=lateral_separation, vertical_separation=vertical_separation, ): # Next step is to check the 2D footprint of the trajectories # intersect. Before computing the intersection we bufferize the # trajectories by half the requested separation. first_shape = first.project_shape(projection) second_shape = second.project_shape(projection) if first_shape is None or second_shape is None: continue if not first_shape.is_valid or not second_shape.is_valid: continue first_shape = first_shape.simplify(1e3).buffer(lateral_separation / 2) second_shape = first_shape.simplify(1e3).buffer( lateral_separation / 2) if first_shape.intersects(second_shape): yield first, second t_xyt = (traffic.airborne().compute_xy(projection).assign( round_t=lambda df: df.timestamp.dt.round(round_t))) cumul = list() # Multiprocessing is implemented on each timerange slot only. # TODO: it would probably be more efficient to multiprocess over each # t_chunk rather than multiprocess the distance computation. for _, t_chunk in tqdm(t_xyt.groupby("round_t"), total=len(set(t_xyt.data.round_t))): with ProcessPoolExecutor(max_workers=max_workers) as executor: tasks = { executor.submit(Flight.distance, first, second): ( first.icao24, second.icao24, ) for (first, second) in yield_pairs(traffic.__class__(t_chunk)) } for future in as_completed(tasks): cumul.append(future.result()) return CPA(pd.concat(cumul, sort=False))
p = ccrs.Mollweide(central_longitude=0) threshold = 1e6 if projection == 'robinson': p = ccrs.Robinson(central_longitude=0) threshold = 0 if projection == 'equalearth': p = ccrs.EqualEarth(central_longitude=0) threshold = 0 if projection == 'geostationary': p = ccrs.Geostationary(central_longitude=0) threshold = 0 if projection == 'goodehomolosine': p = ccrs.InterruptedGoodeHomolosine(central_longitude=0) threshold = 0 if projection == 'europp': p = ccrs.EuroPP() threshold = 0 if projection == 'northpolarstereo': p = ccrs.NorthPolarStereo() threshold = 0 if projection == 'southpolarstereo': p = ccrs.SouthPolarStereo() threshold = 0 if projection == 'lambertconformal': p = ccrs.LambertConformal(central_longitude=0) threshold = 0 #---------------------------------------------------------------------------- # DARK BACKGROUND THEME #----------------------------------------------------------------------------
@author: cdholmes """ import matplotlib.pyplot as plt from owslib.wmts import WebMapTileService import cartopy.crs as ccrs # Location of online data URL = 'https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/wmts.cgi' wmts = WebMapTileService(URL) # Select desired dataset and date # Additional datasets are listed here: https://wiki.earthdata.nasa.gov/display/GIBS/GIBS+Available+Imagery+Products layer = 'MODIS_Aqua_CorrectedReflectance_TrueColor' date = '2015-07-01' # Map projection # Additional options: https://scitools.org.uk/cartopy/docs/latest/crs/projections.html mapproj = ccrs.EuroPP() # Clear the figure plt.clf() # Create the plot axes with desired projection ax = plt.subplot( 111, projection=mapproj ) # Add the dataset ax.add_wmts( wmts, layer, wmts_kwargs={'time': date} )
def cuteplot(gpd_df, crs="Mollweide", title=None, kdp=False, map_extend=(-27, 45, 33, 73.5), bw=0.2): ''' Function to leverage the cartopy library to plot geographical data ''' import matplotlib.pyplot as plt import cartopy.crs as ccrs import cartopy.feature as cfeature import seaborn as sns # map projections proj = { "PlateCarree": ("+proj=eqc +lat_ts=0 +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs", ccrs.PlateCarree()), "Mollweide": ("+proj=moll +lon_0=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs", ccrs.Mollweide()), "Robinson": ("+proj=robin +lon_0=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs", ccrs.Robinson()), "UTM32N": ("+proj=utm +zone=32 +ellps=intl +units=m +no_defs", ccrs.EuroPP()), "Orthographic": ("+proj=ortho", ccrs.Orthographic()) } # plot figure fig = plt.figure() ax = plt.axes(projection=proj.get(crs)[1]) # add features ax.coastlines(resolution='50m') ax.stock_img() countries = cfeature.NaturalEarthFeature( category='cultural', name='admin_0_boundary_lines_land', scale='50m', facecolor='none', edgecolor="black") ax.add_feature(countries) # extend ax.set_extent(map_extend) # plot geopandas data frame if crs != "PlateCarree": gpd_df = gpd_df.to_crs(proj.get(crs)[0]) if kdp: kdp_germany = sns.kdeplot( gpd_df['Target Longitude'], gpd_df['Target Latitude'], # y-axis cmap="viridis", shade=True, shade_lowest=False, bw=bw, transform=ccrs.PlateCarree()) kdp_germany.plot() else: gpd_df.plot(ax=ax, marker='o', color='red', markersize=5, alpha=0.01) # add gridlines ax.gridlines() if title is not None: ax.set_title(title, size=16) plt.tight_layout()
import matplotlib.pyplot as plt import cartopy.crs as ccrs plt.figure(figsize=(2.6153846153846154, 3)) ax = plt.axes(projection=ccrs.EuroPP()) ax.coastlines(resolution='50m') ax.gridlines()
def plot_effects(data: pd.DataFrame, alg: Callable, input_columns: List[str], normalizer: Callable, normalized_columns: List[str], plotted_columns: List[Tuple[str, str]] = [], periodic_columns: List[str] = [], ncols: int = 3, coordinates: Tuple[str, str] = None, bounding_box: Tuple[int, int, int, int] = None, bounding_box_context: Tuple[int, int, int, int] = BOUNDS_NORTHERN_BALTIC_SEA, projection: ccrs.CRS = ccrs.EuroPP(), coastline: bool = False, stock_img: bool = False): """ Visualizes the predictions with respect to different columns by varying one column at a time and setting the rest of the columns to their median values. Parameters: data (pd.DataFrame): Data that is visualized alg (Callable): The prediction algorithm input_columns (List[str]): Names of the columns that the prediction algorithm takes as an input plotted_columns (List[Tuple[str,str]]): List of tuples containing the visualized columns. The first item of each tuple indicates the name of the column in the pandas dataframe and the second item indicates the visualized name normalizer (Callable): The normalizer object that normalizes the data normalized_columns (List[str]): The columns that are normalized periodic_columns (List[str]): The columns that are periodic in nature ncols (int): number of columns in the histogram array, defaults to 3. coordinates (Tuple[str,str]): names of the columns defining latitudes and longitudes bounding_box (Tuple[int,int,int,int]): a Tuple with (longitude min, latitude min, longitude max, latitude max) for the visualized bounding box bounding_box_context (Tuple[int,int,int,int]): a Tuple with (longitude min, latitude min, longitude max, latitude max) for the bounds of the plot projection (ccrs.CRS): Projection used in plotting. defaults to ccrs.EuroPP coastline (bool): If the plot visualizes the coastline stock_img (bool): If the plot visualizes the background title (str): The title of the plot Returns: matplotlib.figure that contains the region """ if len(plotted_columns) == 0: tmp = coordinates or [] plotted_columns = [(col, col) for col in data.columns if col not in tmp] data_median = np.median(data, axis=0) #Set the periodic medians for col in periodic_columns: ind = list(data.columns).index(col) ind_cos, ind_sin = list(data.columns).index("COS" + col), list( data.columns).index("SIN" + col) data_median[ind_cos] = np.cos(data_median[ind] * 2 * np.pi) data_median[ind_sin] = np.sin(data_median[ind] * 2 * np.pi) if coordinates is not None: if len(coordinates) != 2: raise (ValueError) if bounding_box is None: bounding_box = bounding_box_context LAT, LON = np.meshgrid( np.linspace(bounding_box[1], bounding_box[3], num=100), np.linspace(bounding_box[0], bounding_box[2], num=100)) sh = LAT.shape X_ = np.tile(data_median, (sh[0] * sh[1], 1)) X_ = pd.DataFrame(X_, columns=data.columns) X_[coordinates[0]] = LAT.reshape(-1) X_[coordinates[1]] = LON.reshape(-1) X_[normalized_columns] = normalizer.transform(X_[normalized_columns]) Y_pred = alg.predict(X_[input_columns]).reshape(sh) Y_pred = Y_pred - np.min(Y_pred) fig = plt.figure(figsize=(MAPHEIGHT, MAPWIDTH)) ax = plt.axes(projection=projection) if stock_img: ax.stock_img() if coastline: ax.coastlines(resolution='50m') proj_coords = projection.transform_points( ccrs.PlateCarree(), np.array([bounding_box_context[1], bounding_box_context[3]]), np.array([bounding_box_context[0], bounding_box_context[2]])) ax.set_ylim([proj_coords[0, 1], proj_coords[1, 1]]) ax.set_xlim([proj_coords[0, 0], proj_coords[1, 0]]) ax.gridlines(draw_labels=True) #plot_region_in_map(bounding_box, bounding_box_context=bounding_box_context, projection=projection,coastline=coastline, stock_img=coastline) land_50m = cartopy.feature.NaturalEarthFeature('physical', 'land', '50m', edgecolor='gray', facecolor='white') plt.contourf(LON, LAT, Y_pred, transform=ccrs.PlateCarree(), cmap='gray') ax.add_feature(land_50m) #scatterplot_in_map(LON, LAT, Y_pred, bounding_box_context=plotting_utils.BOUNDS_NORTHERN_BALTIC_SEA) cbar = plt.colorbar(fraction=0.03, pad=0.1) cbar.set_label('Effect on output', rotation=270) nplots = len(plotted_columns) fig, axs = get_empty_axes(nplots, ncols) for i, (column, column_label) in enumerate(plotted_columns): row, col = i // ncols, i % ncols axs[row, col].set_visible(True) x = np.linspace(np.min(data[column]), np.max(data[column]), num=100) X_ = np.tile(data_median, (x.shape[0], 1)) X_ = pd.DataFrame(X_, columns=data.columns) X_[column] = x if column in periodic_columns: X_['SIN' + column] = np.sin(2 * np.pi * x) X_['COS' + column] = np.cos(2 * np.pi * x) X_[normalized_columns] = normalizer.transform(X_[normalized_columns]) y_pred = alg.predict(X_[input_columns]).reshape(-1) axs[row, col].plot(x, y_pred - np.min(y_pred), c='k') axs[row, col].set_xlabel(column_label) axs[row, col].set_ylabel('Effect on output')
def countries(**kwargs): params = { "category": "cultural", "name": "admin_0_countries", "scale": "10m", "edgecolor": "#524c50", "facecolor": "none", "alpha": 0.5, **kwargs, } return feature.NaturalEarthFeature(**params) e = crs.EuroPP() fig, ax = plt.subplots(2, 2, figsize=(10, 10), subplot_kw=dict(projection=e)) ville_ac = df.query('nom.str.match(".*\w{2}ac(-|$).*")', engine="python") ville_ay = df.query('nom.str.match(".*\w{2}ay(-|$).*")', engine="python") for ax_ in ax.ravel(): ax_.add_feature(countries(scale="50m")) ax_.set_extent((-4, 9, 42, 51)) ville_ac.plot.scatter( ax=ax[0, 0], x="longitude", y="latitude", transform=crs.PlateCarree(), color="C3",
def plot_orbit_var(lat, lon, var, vmin, vmax, projection, filestr, titlestr, varstr): x = lon[::10, ::10] y = lat[::10, ::10] z = var[::10, ::10] fig = plt.figure() if projection == 'platecarree': p = ccrs.PlateCarree(central_longitude=0) threshold = 0 if projection == 'mollweide': p = ccrs.Mollweide(central_longitude=0) threshold = 1e6 if projection == 'robinson': p = ccrs.Robinson(central_longitude=0) threshold = 0 if projection == 'equalearth': p = ccrs.EqualEarth(central_longitude=0) threshold = 0 if projection == 'geostationary': p = ccrs.Geostationary(central_longitude=0) threshold = 0 if projection == 'goodehomolosine': p = ccrs.InterruptedGoodeHomolosine(central_longitude=0) threshold = 0 if projection == 'europp': p = ccrs.EuroPP() threshold = 0 if projection == 'northpolarstereo': p = ccrs.NorthPolarStereo() threshold = 0 if projection == 'southpolarstereo': p = ccrs.SouthPolarStereo() threshold = 0 if projection == 'lambertconformal': p = ccrs.LambertConformal(central_longitude=0) threshold = 0 ax = plt.axes(projection=p) ax.stock_img() ax.coastlines(resolution='50m') ax.gridlines() colormap = 'gnuplot2' g = ccrs.Geodetic() trans = ax.projection.transform_points(g, x, y) x0 = trans[:, :, 0] x1 = trans[:, :, 1] if projection == 'platecarree': ax.set_extent([-180, 180, -90, 90], crs=p) gl = ax.gridlines(crs=p, draw_labels=True, linewidth=1, color='gray', alpha=0.5, linestyle='-') gl.xlabels_top = False gl.ylabels_right = False gl.xlines = True gl.ylines = True gl.xlocator = mticker.FixedLocator([-180, -120, -60, 0, 60, 120, 180]) gl.ylocator = mticker.FixedLocator([-90, -60, -30, 0, 30, 60, 90]) gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER for mask in (x0 >= threshold, x0 <= threshold): im = ax.pcolor(ma.masked_where(mask, x), ma.masked_where(mask, y), ma.masked_where(mask, z), vmin=vmin, vmax=vmax, transform=ax.projection, cmap=colormap) else: for mask in (x0 >= threshold, x0 <= threshold): im = ax.pcolor(ma.masked_where(mask, x0), ma.masked_where(mask, x1), ma.masked_where(mask, z), vmin=vmin, vmax=vmax, transform=ax.projection, cmap=colormap) im.set_clim(vmin, vmax) cb = plt.colorbar(im, orientation="horizontal", extend='both', label=varstr) plt.title(titlestr) plt.savefig(filestr) plt.close('all') return
'AzimuthalEquidistant': ccrs.AzimuthalEquidistant(), 'EquidistantConic': ccrs.EquidistantConic(), 'LambertConformal': ccrs.LambertConformal(), 'LambertCylindrical': ccrs.LambertCylindrical(), 'Mercator': ccrs.Mercator(), 'Miller': ccrs.Miller(), 'Mollweide': ccrs.Mollweide(), 'Orthographic': ccrs.Orthographic(), 'Robinson': ccrs.Robinson(), 'Sinusoidal': ccrs.Sinusoidal(), 'Stereographic': ccrs.Stereographic(), 'TransverseMercator': ccrs.TransverseMercator(), 'InterruptedGoodeHomolosine': ccrs.InterruptedGoodeHomolosine(), 'RotatedPole': ccrs.RotatedPole(), 'OSGB': ccrs.OSGB(), 'EuroPP': ccrs.EuroPP(), 'Geostationary': ccrs.Geostationary(), 'NearsidePerspective': ccrs.NearsidePerspective(), 'EckertI': ccrs.EckertI(), 'EckertII': ccrs.EckertII(), 'EckertIII': ccrs.EckertIII(), 'EckertIV': ccrs.EckertIV(), 'EckertV': ccrs.EckertV(), 'EckertVI': ccrs.EckertVI(), 'Gnomonic': ccrs.Gnomonic(), 'LambertAzimuthalEqualArea': ccrs.LambertAzimuthalEqualArea(), 'NorthPolarStereo': ccrs.NorthPolarStereo(), 'OSNI': ccrs.OSNI(), 'SouthPolarStereo': ccrs.SouthPolarStereo() }