def __init__(self, figsize=(6,5), tiler = Stamen('terrain-background'), zoom=9, cmap='magma_r', \ title_size=12, label_size=11, plot_coast='10m',\ proj='plate_carree', margins=(-0.1, 0.15, -0.1, 0.1), \ subplots_adjust=(0.1, 0.05, 0.95, 0.95, None, None), \ grid_linewidth=1, grid_linestyle=':', grid_color = 'k', grid_alpha=0.8, \ extend='both', cbar_kwargs={'shrink':0.9},title=None, \ vmin=None, vmax=None, levels=None): ''' Instance method for class PlotConfig Args: figsize(tuple): (x_inches, y_inches) tiler(): tile or None zoom(int): Zoom for tile between 1 and 9 when tiler is specified. cmap(str): matplotlib colormap title_size(int): Font size for title or None for default label_size(int): Font size for label or None for default plot_coast(str): [ '10m' | '50m' | '110m' | None ] Plotting coastline proj(str): [ 'plate_carree' | None ] Set in case of lon-lat coordinates) margins(tuple): Margins in float for (L, B, R, T) in normalized coords between 0 and 1 subplots_adjust(tuple): (L, B, R, T, wspace=None, hspace=None) for Figure.subplots_adjust() grid_linewidth(int|float): Grid line width grid_linestyle(str): Grid line style grid_color(str): Grid color grid_alpha(float): Grid alpha (opacity) cbar_kwargs(dict): kwargs for color bar 'shrink' adjusts the length of color bar extend(str): [ 'neither' | 'both' | 'min' | 'max' ] If not 'neither', make pointed end(s) for out-of- range values. These are set for a given colormap using the colormap set_under and set_over methods. vmin(float): vmin for cbar or None for default vmax(float): vmax for cbar or None for default levels(int | array-like): levels for cbar (int: num of levels, array-like: level values) or None for default ''' self.figsize = figsize self.tiler = tiler self.zoom = zoom self.cmap = cmap self.title_size = title_size self.label_size = label_size ## self.ticks_intervals = ticks_intervals ## ticks depends on plotting -> Plotter self.plot_coast = plot_coast self.proj = proj self.margins = margins self.subplots_adjust = subplots_adjust self.grid_linewidth = grid_linewidth self.grid_linestyle = grid_linestyle self.grid_color = grid_color self.grid_alpha = grid_alpha self.extend = extend self.cbar_kwargs = cbar_kwargs self.vmin = vmin self.vmax = vmax self.levels = levels self.title = title
def plot_overview(): """ Plots overview over geographic locations of gauges available in the dataset. """ try: from cartopy.io.img_tiles import Stamen from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter import cartopy.crs as ccrs tiler = Stamen("terrain") mercator = tiler.crs f = plt.figure(figsize = (10, 8)) gs = GridSpec(1, 2, width_ratios=[1.0, 0.03]) ax = plt.subplot(gs[0], projection=mercator) ax.set_extent([-130, -60, 20, 50]) ax.add_image(tiler, 5) #ax.coastlines('10m', lw=0.5) ax.set_xlabel("Longitude") ax.set_ylabel("Latitude") xticks = np.arange(-135, -64, 10) yticks = np.arange(25, 46, 10) ax.set_xticks(xticks, crs=ccrs.PlateCarree()) ax.set_yticks(yticks, crs=ccrs.PlateCarree()) lon_formatter = LongitudeFormatter(zero_direction_label=True) lat_formatter = LatitudeFormatter() ax.xaxis.set_major_formatter(lon_formatter) ax.yaxis.set_major_formatter(lat_formatter) img=ax.scatter(gauge_information["longitude"], gauge_information["latitude"], transform=ccrs.PlateCarree(), c=gauge_information["gauge id"], s=2, cmap="plasma") ax.set_title("Geographic locations of gauges in CAMELS dataset") asp = ax.get_aspect() ax = plt.subplot(gs[1]) cb = plt.colorbar(img, label="Gauge ID", cax=ax) cb.formatter.set_useOffset(False) cb.formatter.set_scientific(False) cb.formatter.set_powerlimits((-10, 20)) cb.update_ticks() plt.tight_layout() except: url = "http://spfrnd.de/datasets/camels/overview.png" img = plt.imread(url) plt.imshow(img) plt.gca().set_axis_off()
def test_radarmapdisplay_cartopy_preexisting_ax(outfile=None): import cartopy from cartopy.io.img_tiles import Stamen radar = pyart.io.read_cfradial(pyart.testing.CFRADIAL_PPI_FILE) display = pyart.graph.RadarMapDisplay(radar, shift=(0.1, 0.0)) fig = plt.figure() ax = plt.axes(projection=cartopy.crs.PlateCarree()) ax.add_image(Stamen('terrain-background'), 6) display.plot_ppi_map('reflectivity_horizontal', 0, ax=ax, embelish=False) if outfile: fig.savefig(outfile) plt.close()
def main(): tiler = Stamen('terrain-background') mercator = tiler.crs fig = plt.figure() ax = fig.add_subplot(1, 1, 1, projection=mercator) ax.set_extent([-90, -73, 22, 34], crs=ccrs.PlateCarree()) ax.add_image(tiler, 6) ax.coastlines('10m') plt.show()
def make_map_cartopy(projection=ccrs.PlateCarree()): """ Generate fig and ax using cartopy input: projection output: fig and ax """ alpha = 0.5 subplot_kw = dict(projection=projection) fig, ax = plt.subplots(figsize=(12, 8), subplot_kw=subplot_kw) gl = ax.gridlines(draw_labels=True) gl.xlabels_top = gl.ylabels_right = False gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER if False: # Put a background image on for nice sea rendering. ax.stock_img() # Create a feature for States/Admin 1 regions at 1:50m from Natural Earth states_provinces = cfeature.NaturalEarthFeature( category='cultural', name='admin_1_states_provinces_lines', scale='100m', facecolor='none') SOURCE = 'Natural Earth' LICENSE = 'public domain' ax.add_feature(cfeature.LAND, zorder=0, alpha=alpha) ax.add_feature(cfeature.COASTLINE, zorder=1, alpha=alpha) ax.add_feature(cfeature.BORDERS, zorder=1, alpha=2 * alpha) ax.add_feature(states_provinces, edgecolor='gray', zorder=1) # Add a text annotation for the license information to the # the bottom right corner. text = AnchoredText(r'$\mathcircled{{c}}$ {}; license: {}' ''.format(SOURCE, LICENSE), loc=4, prop={'size': 9}, frameon=True) ax.add_artist(text) else: tiler = Stamen('terrain-background') ax.add_image(tiler, 6) ax.coastlines('10m') ax.set_ylim(18.752631, 32) #lat limits ax.set_xlim(46.879415, 70.123184) #lon limits return fig, ax
def main(): tiler = Stamen('terrain-background') #tiler = Stamen('toner') mercator = tiler.crs fig = plt.figure(figsize=(12, 8)) ax = fig.add_subplot(1, 1, 1, projection=mercator) ax.set_extent([-111.9, -108.2, 34.4, 36.9], crs=ccrs.PlateCarree()) ax.add_image(tiler, 8) ax.plot(-109.221, 36.3061, 'bo', markersize=10, transform=ccrs.Geodetic()) ax.text(-109.221, 36.35, 'Tsaile', transform=ccrs.Geodetic(), fontsize=16) plt.show()
def _plot_geographic_context(ax, utm, hires=False): """ Plot geographic basemap information on a map axis. Plots a background image for UTM-projected plots and simple coastlines for unprojected plots. Args: ax (:class:`~cartopy.mpl.geoaxes.GeoAxes`): Existing axis to plot into utm (bool): Flag specifying if the axis is projected to UTM or not hires (bool): If `True`, use higher-resolution images/coastlines (default: `False`) """ # Since projected grids cover less area and may not include coastlines, # use a background image to provide geographical context (can be slow) if utm: if hires: zoom_level = 12 else: zoom_level = 8 ax.add_image(Stamen(style='terrain-background'), zoom_level) # Since unprojected grids have regional/global extent, just show the # coastlines else: if hires: gshhs_scale = 'intermediate' lake_scale = '10m' else: gshhs_scale = 'low' lake_scale = '50m' ax.add_feature( cfeature.GSHHSFeature(scale=gshhs_scale), facecolor=cfeature.COLORS['land'], zorder=0, ) ax.background_patch.set_facecolor(cfeature.COLORS['water']) ax.add_feature( cfeature.LAKES.with_scale(lake_scale), facecolor=cfeature.COLORS['water'], edgecolor='black', zorder=0, )
def main(): tiler = Stamen('terrain-background') mercator = tiler.crs lons, lats, ints = sample_data() track = sgeom.LineString(zip(lons, lats)) best_track = buid_best_track() fig = plt.figure(figsize=(40, 20)) ax = fig.add_subplot(1, 1, 1, projection=mercator) ax.set_extent([100, 180, 0, 40], crs=ccrs.PlateCarree()) ax.add_image(tiler, 6) ax.add_geometries([track], ccrs.PlateCarree(), facecolor='none', edgecolor='k', linewidth=0.6) for k, v in best_track.items(): trace = list(zip(*v)) if len(trace) == 0: continue catelon = trace[0] catelat = trace[1] ax.plot(catelon, catelat, markersize=5, marker='o', linestyle='', color=colors[k], transform=ccrs.PlateCarree(), label=k) ax.set_xticks([100, 110, 120, 130, 140, 150, 160, 170, 180], crs=ccrs.PlateCarree()) ax.set_yticks([0, 10, 20, 30, 40], crs=ccrs.PlateCarree()) lon_formatter = LongitudeFormatter(zero_direction_label=True) lat_formatter = LatitudeFormatter() ax.xaxis.set_major_formatter(lon_formatter) ax.yaxis.set_major_formatter(lat_formatter) ax.coastlines('10m') ax.legend() # add a legend plt.savefig('typhoon.png') # 保存图片 plt.show()
def _plot_geographic_context(ax, utm, hires=False): """ Plot geographic basemap information on a map axis. Plots a background image for UTM-projected plots and simple coastlines for unprojected plots. Args: ax: Existing GeoAxes to plot into utm: Flag specifying if the axis is projected to UTM or not hires: If True, use higher-resolution images/coastlines (default: False) """ # Since projected grids cover less area and may not include coastlines, # use a background image to provide geographical context (can be slow) if utm: if hires: zoom_level = 12 else: zoom_level = 8 ax.add_image(Stamen(style='terrain-background'), zoom_level, zorder=-1) # Since unprojected grids have regional/global extent, just show the # coastlines else: if hires: scale = '10m' else: scale = '50m' land = cfeature.LAND.with_scale(scale) ax.add_feature(land, facecolor=cfeature.COLORS['land'], edgecolor='black') ax.background_patch.set_facecolor(cfeature.COLORS['water']) lakes = cfeature.LAKES.with_scale(scale) ax.add_feature(lakes, facecolor=cfeature.COLORS['water'], edgecolor='black', zorder=0)
def geoplot(self, data_field=None, lat_field='lat', lon_field='lon', dsname=None, cbar_label=None, title=None, projection=ccrs.PlateCarree(), plot_buffer=0.08, stamen='terrain-background', tile=8, cartopy_feature=None, cmap='rainbow', text=None, gridlines=True, **kwargs): """ Creates a latttude and longitude plot of a time series data set with data values indicated by color and described with a colorbar. Latitude values must be in degree north (-90 to 90) and longitude must be in degree east (-180 to 180). Parameters ---------- data_field: str Name of data filed in object to plot. lat_field: str Name of latitude field in object to use. lon_field: str Name of longitude field in object to use. dsname: str or None The name of the datastream to plot. Set to None to make ACT attempt to automatically determine this. cbar_label: str Label to use with colorbar. If set to None will attempt to create label from long_name and units. title: str Plot title. projection: str Project to use on plot. plot_buffer: float Buffer to add around data on plot in lat and lon dimension stamen: str Dataset to use for background image. Set to None to not use background image. tile: int Tile zoom to use with background image. Higer number indicates more resolution. A value of 8 is typical for a normal sonde plot. cartopy_feature: list of str or str Cartopy feature to add to plot. cmap: str Color map to use for colorbar. text: dictionary Dictionary of {text:[lon,lat]} to add to plot. Can have more than one set of text to add. gridlines: boolean Use latitude and longitude gridlines. **kwargs: keyword arguments Any other keyword arguments that will be passed into :func:`matplotlib.pyplot.scatter` when the figure is made. See the matplotlib documentation for further details on what keyword arguments are available. """ # Get current plotting figure # del self.axes # if self.fig is None: # self.fig = plt.figure() if dsname is None and len(self._arm.keys()) > 1: raise ValueError(("You must choose a datastream when there are 2 " "or more datasets in the GeographicPlotDisplay " "object.")) elif dsname is None: dsname = list(self._arm.keys())[0] if data_field is None: raise ValueError(("You must enter the name of the data " "to be plotted.")) # Extract data from object try: lat = self._arm[dsname][lat_field].values except KeyError: raise ValueError(("You will need to provide the name of the " "field if not '{}' to use for latitued " "data.").format(lat_field)) try: lon = self._arm[dsname][lon_field].values except KeyError: raise ValueError(("You will need to provide the name of the " "field if not '{}' to use for longitude " "data.").format(lon_field)) # Set up metadata information for display on plot if cbar_label is None: try: cbar_label = ( self._arm[dsname][data_field].attrs['long_name'] + ' (' + self._arm[dsname][data_field].attrs['units'] + ')') except KeyError: cbar_label = data_field lat_limits = [np.nanmin(lat), np.nanmax(lat)] lon_limits = [np.nanmin(lon), np.nanmax(lon)] box_size = np.max( [np.abs(np.diff(lat_limits)), np.abs(np.diff(lon_limits))]) bx_buf = box_size * plot_buffer lat_center = np.sum(lat_limits) / 2. lon_center = np.sum(lon_limits) / 2. lat_limits = [ lat_center - box_size / 2. - bx_buf, lat_center + box_size / 2. + bx_buf ] lon_limits = [ lon_center - box_size / 2. - bx_buf, lon_center + box_size / 2. + bx_buf ] data = self._arm[dsname][data_field].values # Create base plot projection ax = plt.axes(projection=projection) plt.subplots_adjust(left=0.01, right=0.99, bottom=0.05, top=0.93) ax.set_extent( [lon_limits[0], lon_limits[1], lat_limits[0], lat_limits[1]], crs=projection) if title is None: try: dim = list(self._arm[dsname][data_field].dims) ts = pd.to_datetime(str(self._arm[dsname][dim[0]].values[0])) date = ts.strftime('%Y-%m-%d') time_str = ts.strftime('%H:%M:%S') plt.title(' '.join([dsname, 'at', date, time_str])) except NameError: plt.title(dsname) else: plt.title(title) if stamen: tiler = Stamen(stamen) ax.add_image(tiler, tile) colorbar_map = None if cmap is not None: colorbar_map = plt.cm.get_cmap(cmap) sc = ax.scatter(lon, lat, c=data, cmap=colorbar_map, **kwargs) cbar = plt.colorbar(sc) cbar.ax.set_ylabel(cbar_label) if cartopy_feature is not None: if isinstance(cartopy_feature, str): cartopy_feature = [cartopy_feature] cartopy_feature = [ii.upper() for ii in cartopy_feature] if 'STATES' in cartopy_feature: ax.add_feature(cfeature.STATES.with_scale('10m')) if 'LAND' in cartopy_feature: ax.add_feature(cfeature.LAND) if 'OCEAN' in cartopy_feature: ax.add_feature(cfeature.OCEAN) if 'COASTLINE' in cartopy_feature: ax.add_feature(cfeature.COASTLINE) if 'BORDERS' in cartopy_feature: ax.add_feature(cfeature.BORDERS, linestyle=':') if 'LAKES' in cartopy_feature: ax.add_feature(cfeature.LAKES, alpha=0.5) if 'RIVERS' in cartopy_feature: ax.add_feature(cfeature.RIVERS) if text is not None: for label, location in text.items(): ax.plot(location[0], location[1], marker='*', color='black') ax.text(location[0], location[1], label, color='black') if gridlines: gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, linewidth=1, color='gray', alpha=0.5, linestyle='--') gl.xlabels_top = False gl.ylabels_left = True gl.xlabels_bottom = True gl.ylabels_right = False gl.xlabel_style = {'size': 6, 'color': 'gray'} gl.ylabel_style = {'size': 6, 'color': 'gray'} return ax
def plot_pos_map(lat, lon, alt, fname_list, ax=None, fig=None, save_fig=True, sort_altitude='No', dpi=72, alpha=1., cb_label='height [m MSL]', titl='Position', xlabel='Lon [Deg]', ylabel='Lat [Deg]', limits=None, vmin=None, vmax=None, lon_step=0.3, lat_step=0.1, background_zoom=8): """ plots a trajectory on a map Parameters ---------- lat, lon, alt : float array Points coordinates fname_list : list of str list of names of the files where to store the plot fig : Figure Figure to add the colorbar to. If none a new figure will be created ax : Axis Axis to plot on. if fig is None a new axis will be created save_fig : bool if true save the figure if false it does not close the plot and returns the handle to the figure sort_altitude : str String indicating whether to sort the altitude data. Can be 'No', 'Lowest_on_top' or 'Highest_on_top' dpi : int Pixel density alpha : float Transparency cb_label : str Color bar label titl : str Plot title xlabel, ylabel : str The labels of the X and Y axis limits : tupple or None The limits of the field to plot vmin, vmax : float The limits of the color scale lon_step, lat_step : float The step interval of the latitude, longitude lines to plot background_zoom : int The zoom of the background image. A higher number will give more level of detail at the expense of speed. Returns ------- fname_list : list of str or fig, ax : tupple list of names of the saved plots or handle of the figure an axes """ if not _CARTOPY_AVAILABLE: warn('Unable to plot trajectory on a map. Cartopy not available') return [''] if sort_altitude in ('Lowest_on_top', 'Highest_on_top'): ind = np.argsort(alt) if sort_altitude == 'Lowest_on_top': ind = ind[::-1] lat = lat[ind] lon = lon[ind] alt = alt[ind] if vmin is None: vmin = alt.min() if vmax is None: vmax = alt.max() marker = 'x' col = alt cmap = 'viridis' norm = plt.Normalize(vmin, vmax) # get background map instance stamen_terrain = Stamen('terrain-background') projection = cartopy.crs.PlateCarree() # set map limits and lat/lon lines if limits is None: limits = [np.min(lon), np.max(lon), np.min(lat), np.max(lat)] lon_lines = np.arange(limits[0], limits[1]+1, lon_step) lat_lines = np.arange(limits[2], limits[3]+1, lat_step) if fig is None: fig = plt.figure(figsize=[10, 8], dpi=dpi) # draw background ax = fig.add_subplot(111, projection=stamen_terrain.crs) ax.set_extent(limits, crs=projection) ax.add_image(stamen_terrain, background_zoom) # add countries countries = cartopy.feature.NaturalEarthFeature( category='cultural', name='admin_0_countries', scale='10m', facecolor='none') ax.add_feature(countries, edgecolor='black') # draw grid lines and labels gl = ax.gridlines(xlocs=lon_lines, ylocs=lat_lines, draw_labels=True) gl.xlabels_top = False gl.ylabels_right = False ax.text(0.5, -0.2, xlabel, va='bottom', ha='center', rotation='horizontal', rotation_mode='anchor', transform=ax.transAxes) ax.text(-0.1, 0.55, ylabel, va='bottom', ha='center', rotation='vertical', rotation_mode='anchor', transform=ax.transAxes) else: ax.autoscale(False) # plot data cax = ax.scatter( lon, lat, c=col, marker=marker, alpha=alpha, cmap=cmap, norm=norm, transform=projection) # plot colorbar cb = fig.colorbar(cax, orientation='horizontal') cb.set_label(cb_label) ax.set_title(titl) if save_fig: for fname in fname_list: fig.savefig(fname, dpi=dpi) plt.close(fig) return fname_list return (fig, ax)
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 plot_ppi_map(self, field, sweep=0, mask_tuple=None, vmin=None, vmax=None, cmap=None, norm=None, mask_outside=False, title=None, title_flag=True, colorbar_flag=True, colorbar_label=None, ax=None, fig=None, lat_lines=None, lon_lines=None, projection=None, min_lon=None, max_lon=None, min_lat=None, max_lat=None, width=None, height=None, lon_0=None, lat_0=None, resolution='110m', shapefile=None, shapefile_kwargs=None, edges=True, gatefilter=None, filter_transitions=True, embelish=True, maps_list=['countries', 'coastlines'], raster=False, ticks=None, ticklabs=None, alpha=None, background_zoom=8): """ Plot a PPI volume sweep onto a geographic map. Parameters ---------- field : str Field to plot. sweep : int, optional Sweep number to plot. Other Parameters ---------------- mask_tuple : (str, float) Tuple containing the field name and value below which to mask field prior to plotting, for example to mask all data where NCP < 0.5 set mask_tuple to ['NCP', 0.5]. None performs no masking. vmin : float Luminance minimum value, None for default value. Parameter is ignored is norm is not None. vmax : float Luminance maximum value, None for default value. Parameter is ignored is norm is not None. norm : Normalize or None, optional matplotlib Normalize instance used to scale luminance data. If not None the vmax and vmin parameters are ignored. If None, vmin and vmax are used for luminance scaling. cmap : str or None Matplotlib colormap name. None will use the default colormap for the field being plotted as specified by the Py-ART configuration. mask_outside : bool True to mask data outside of vmin, vmax. False performs no masking. title : str Title to label plot with, None to use default title generated from the field and tilt parameters. Parameter is ignored if title_flag is False. title_flag : bool True to add a title to the plot, False does not add a title. colorbar_flag : bool True to add a colorbar with label to the axis. False leaves off the colorbar. ticks : array Colorbar custom tick label locations. ticklabs : array Colorbar custom tick labels. colorbar_label : str Colorbar label, None will use a default label generated from the field information. ax : Cartopy GeoAxes instance If None, create GeoAxes instance using other keyword info. If provided, ax must have a Cartopy crs projection and projection kwarg below is ignored. fig : Figure Figure to add the colorbar to. None will use the current figure. lat_lines, lon_lines : array or None Locations at which to draw latitude and longitude lines. None will use default values which are resonable for maps of North America. projection : cartopy.crs class Map projection supported by cartopy. Used for all subsequent calls to the GeoAxes object generated. Defaults to LambertConformal centered on radar. min_lat, max_lat, min_lon, max_lon : float Latitude and longitude ranges for the map projection region in degrees. width, height : float Width and height of map domain in meters. Only this set of parameters or the previous set of parameters (min_lat, max_lat, min_lon, max_lon) should be specified. If neither set is specified then the map domain will be determined from the extend of the radar gate locations. shapefile : str Filename for a shapefile to add to map. shapefile_kwargs : dict Key word arguments used to format shapefile. Projection defaults to lat lon (cartopy.crs.PlateCarree()) resolution : '10m', '50m', '110m'. Resolution of NaturalEarthFeatures to use. See Cartopy documentation for details. gatefilter : GateFilter GateFilter instance. None will result in no gatefilter mask being applied to data. filter_transitions : bool True to remove rays where the antenna was in transition between sweeps from the plot. False will include these rays in the plot. No rays are filtered when the antenna_transition attribute of the underlying radar is not present. edges : bool True will interpolate and extrapolate the gate edges from the range, azimuth and elevations in the radar, treating these as specifying the center of each gate. False treats these coordinates themselved as the gate edges, resulting in a plot in which the last gate in each ray and the entire last ray are not not plotted. embelish: bool True by default. Set to False to supress drawing of coastlines etc.. Use for speedup when specifying shapefiles. Note that lat lon labels only work with certain projections. maps_list: list of strings if embelish is true the list of maps to use. default countries, coastlines raster : bool False by default. Set to true to render the display as a raster rather than a vector in call to pcolormesh. Saves time in plotting high resolution data over large areas. Be sure to set the dpi of the plot for your application if you save it as a vector format (i.e., pdf, eps, svg). alpha : float or None Set the alpha transparency of the radar plot. Useful for overplotting radar over other datasets. background_zoom : int Zoom of the background image. A highest number provides more detail at the cost of processing speed """ # parse parameters ax, fig = parse_ax_fig(ax, fig) vmin, vmax = parse_vmin_vmax(self._radar, field, vmin, vmax) cmap = parse_cmap(cmap, field) if norm is not None: # if norm is set do not override with vmin/vmax vmin = vmax = None if lat_lines is None: lat_lines = np.arange(30, 46, 1) if lon_lines is None: lon_lines = np.arange(-110, -75, 1) lat_0 = self.loc[0] lon_0 = self.loc[1] # get data for the plot data = self._get_data(field, sweep, mask_tuple, filter_transitions, gatefilter) x, y = self._get_x_y(sweep, edges, filter_transitions) # mask the data where outside the limits if mask_outside: data = np.ma.masked_outside(data, vmin, vmax) # If background map is used the plot projection should be # that of the map if 'relief' in maps_list: tiler = Stamen('terrain-background') projection = tiler.crs ax = plt.axes(projection=projection) warnings.warn( 'The projection of the image is set to that of the ' + 'background map, i.e. ' + str(projection), UserWarning) elif hasattr(ax, 'projection'): projection = ax.projection else: # initialize instance of GeoAxes if not provided if projection is None: # set map projection to LambertConformal if none is # specified projection = cartopy.crs.LambertConformal( central_longitude=lon_0, central_latitude=lat_0) warnings.warn( "No projection was defined for the axes." + " Overridding defined axes and using default " + "projection " + str(projection), UserWarning) ax = plt.axes(projection=projection) if min_lon: ax.set_extent([min_lon, max_lon, min_lat, max_lat], crs=cartopy.crs.PlateCarree()) elif width: ax.set_extent([-width / 2., width / 2., -height / 2., height / 2.], crs=self.grid_projection) # plot the data pm = ax.pcolormesh(x * 1000., y * 1000., data, alpha=alpha, vmin=vmin, vmax=vmax, cmap=cmap, norm=norm, transform=self.grid_projection) # plot as raster in vector graphics files if raster: pm.set_rasterized(True) # add embelishments if embelish is True: for cartomap in maps_list: if cartomap == 'relief': ax.add_image(tiler, background_zoom) elif cartomap == 'countries': # add countries countries = cartopy.feature.NaturalEarthFeature( category='cultural', name='admin_0_countries', scale=resolution, facecolor='none') ax.add_feature(countries, edgecolor='black') elif cartomap == 'provinces': # Create a feature for States/Admin 1 regions at # 1:resolution from Natural Earth states_provinces = cartopy.feature.NaturalEarthFeature( category='cultural', name='admin_1_states_provinces_lines', scale=resolution, facecolor='none') ax.add_feature(states_provinces, edgecolor='gray') elif cartomap == 'urban_areas' and resolution in ('10m', '50m'): urban_areas = cartopy.feature.NaturalEarthFeature( category='cultural', name='urban_areas', scale=resolution) ax.add_feature(urban_areas, edgecolor='brown', facecolor='brown', alpha=0.25) elif cartomap == 'roads' and resolution == '10m': roads = cartopy.feature.NaturalEarthFeature( category='cultural', name='roads', scale=resolution) ax.add_feature(roads, edgecolor='red', facecolor='none') elif cartomap == 'railroads' and resolution == '10m': railroads = cartopy.feature.NaturalEarthFeature( category='cultural', name='railroads', scale=resolution) ax.add_feature(railroads, edgecolor='green', facecolor='none', linestyle=':') elif cartomap == 'coastlines': ax.coastlines(resolution=resolution) elif cartomap == 'lakes': # add lakes lakes = cartopy.feature.NaturalEarthFeature( category='physical', name='lakes', scale=resolution) ax.add_feature(lakes, edgecolor='blue', facecolor='blue', alpha=0.25) elif resolution == '10m' and cartomap == 'lakes_europe': lakes_europe = cartopy.feature.NaturalEarthFeature( category='physical', name='lakes_europe', scale=resolution) ax.add_feature(lakes_europe, edgecolor='blue', facecolor='blue', alpha=0.25) elif cartomap == 'rivers': # add rivers rivers = cartopy.feature.NaturalEarthFeature( category='physical', name='rivers_lake_centerlines', scale=resolution) ax.add_feature(rivers, edgecolor='blue', facecolor='none') elif resolution == '10m' and cartomap == 'rivers_europe': rivers_europe = cartopy.feature.NaturalEarthFeature( category='physical', name='rivers_europe', scale=resolution) ax.add_feature(rivers_europe, edgecolor='blue', facecolor='none') elif cartomap == 'populated_places': ax = _add_populated_places(ax, resolution=resolution) else: warnings.warn( 'map ' + cartomap + ' for resolution ' + resolution + ' not available', UserWarning) # labeling gridlines poses some difficulties depending on the # projection, so we need some projection-spectific methods if isinstance(ax.projection, (cartopy.crs.PlateCarree, cartopy.crs.Mercator)): gl = ax.gridlines(xlocs=lon_lines, ylocs=lat_lines, draw_labels=True) gl.xlabels_top = False gl.ylabels_right = False ax.text(0.5, -0.1, 'longitude [deg]', va='bottom', ha='center', rotation='horizontal', rotation_mode='anchor', transform=ax.transAxes) ax.text(-0.12, 0.55, 'latitude [deg]', va='bottom', ha='center', rotation='vertical', rotation_mode='anchor', transform=ax.transAxes) elif isinstance(ax.projection, cartopy.crs.LambertConformal): fig.canvas.draw() ax.gridlines(xlocs=lon_lines, ylocs=lat_lines) # Label the end-points of the gridlines using the custom # tick makers: ax.xaxis.set_major_formatter( cartopy.mpl.gridliner.LONGITUDE_FORMATTER) ax.yaxis.set_major_formatter( cartopy.mpl.gridliner.LATITUDE_FORMATTER) if _LAMBERT_GRIDLINES: lambert_xticks(ax, lon_lines) lambert_yticks(ax, lat_lines) else: ax.gridlines(xlocs=lon_lines, ylocs=lat_lines) # plot the data and optionally the shape file # we need to convert the radar gate locations (x and y) which are in # km to meters we also need to give the original projection of the # data which is stored in self.grid_projection if shapefile is not None: from cartopy.io.shapereader import Reader if shapefile_kwargs is None: shapefile_kwargs = {} if 'crs' not in shapefile_kwargs: shapefile_kwargs['crs'] = cartopy.crs.PlateCarree() ax.add_geometries( Reader(shapefile).geometries(), **shapefile_kwargs) if title_flag: self._set_title(field, sweep, title, ax) # add plot and field to lists self.plots.append(pm) self.plot_vars.append(field) if colorbar_flag: self.plot_colorbar(mappable=pm, label=colorbar_label, field=field, fig=fig, ax=ax, ticks=ticks, ticklabs=ticklabs) # keep track of this GeoAxes object for later self.ax = ax
def main(): # Define the two coordinate systems with different ellipses. wgs84 = ccrs.PlateCarree(globe=ccrs.Globe(datum='WGS84', ellipse='WGS84')) sphere = ccrs.PlateCarree( globe=ccrs.Globe(datum='WGS84', ellipse='sphere')) # Define the coordinate system of the data we have from Natural Earth and # acquire the 1:10m physical coastline shapefile. geodetic = ccrs.Geodetic(globe=ccrs.Globe(datum='WGS84')) dataset = cfeature.NaturalEarthFeature(category='physical', name='coastline', scale='10m') # Create a Stamen map tiler instance, and use its CRS for the GeoAxes. tiler = Stamen('terrain-background') fig = plt.figure() ax = fig.add_subplot(1, 1, 1, projection=tiler.crs) ax.set_title('The effect of incorrectly referencing the Solomon Islands') # Pick the area of interest. In our case, roughly the Solomon Islands, and # get hold of the coastlines for that area. extent = [155, 163, -11.5, -6] ax.set_extent(extent, geodetic) geoms = list(dataset.intersecting_geometries(extent)) # Add the Stamen aerial imagery at zoom level 7. ax.add_image(tiler, 7) # Transform the geodetic coordinates of the coastlines into the two # projections of differing ellipses. wgs84_geoms = [ geom_transform(transform_fn_factory(wgs84, geodetic), geom) for geom in geoms ] sphere_geoms = [ geom_transform(transform_fn_factory(sphere, geodetic), geom) for geom in geoms ] # Using these differently referenced geometries, assume that they are # both referenced to WGS84. ax.add_geometries(wgs84_geoms, wgs84, edgecolor='white', facecolor='none') ax.add_geometries(sphere_geoms, wgs84, edgecolor='gray', facecolor='none') # Create a legend for the coastlines. legend_artists = [ Line([0], [0], color=color, linewidth=3) for color in ('white', 'gray') ] legend_texts = ['Correct ellipse\n(WGS84)', 'Incorrect ellipse\n(sphere)'] legend = ax.legend(legend_artists, legend_texts, fancybox=True, loc='lower left', framealpha=0.75) legend.legendPatch.set_facecolor('wheat') # Create an inset GeoAxes showing the location of the Solomon Islands. sub_ax = fig.add_axes([0.7, 0.625, 0.2, 0.2], projection=ccrs.PlateCarree()) sub_ax.set_extent([110, 180, -50, 10], geodetic) # Make a nice border around the inset axes. effect = Stroke(linewidth=4, foreground='wheat', alpha=0.5) sub_ax.spines['geo'].set_path_effects([effect]) # Add the land, coastlines and the extent of the Solomon Islands. sub_ax.add_feature(cfeature.LAND) sub_ax.coastlines() extent_box = sgeom.box(extent[0], extent[2], extent[1], extent[3]) sub_ax.add_geometries([extent_box], ccrs.PlateCarree(), facecolor='none', edgecolor='blue', linewidth=2) plt.show()
def draw_G(self, bgcolor='w', no_axis=False, background_map=False, use_geom=False, edge_color='b', edge_linewidth=2, edge_alpha=1, node_size=40, node_color='r', node_alpha=1, node_edgecolor='r', node_zorder=1): if background_map: imagery = Stamen(style='toner-lite') zoom_level = 15 fig, ax = plt.subplots(figsize=self.figsize, subplot_kw={'projection': imagery.crs}) ax.set_extent(self.extent, crs=ccrs.Geodetic()) ax.add_image(imagery, zoom_level, alpha=1, interpolation='bilinear') else: fig, ax = plt.subplots(figsize=self.figsize, facecolor=bgcolor, subplot_kw={'projection': ccrs.Mercator()}) ax.set_extent(self.extent, crs=ccrs.Geodetic()) lines = [] for u, v, data in self.graph.edges(data=True): if 'geometry' in data and use_geom: # if it has a geometry attribute (a list of line segments), add them # to the list of lines to plot xs, ys = data['geometry'].xy lines.append(list(zip(xs, ys))) else: # if it doesn't have a geometry attribute, the edge is a straight # line from node to node x1 = self.graph.nodes[u]['lon'] y1 = self.graph.nodes[u]['lat'] x2 = self.graph.nodes[v]['lon'] y2 = self.graph.nodes[v]['lat'] line = [(x1, y1), (x2, y2)] lines.append(line) # add the lines to the axis as a linecollection lc = collections.LineCollection(lines, colors=edge_color, linewidths=edge_linewidth, alpha=edge_alpha, zorder=2, transform=ccrs.Geodetic()) ax.add_collection(lc) node_Xs = [float(x) for _, x in self.graph.nodes(data='lon')] node_Ys = [float(y) for _, y in self.graph.nodes(data='lat')] ax.scatter(node_Xs, node_Ys, s=node_size, c=node_color, alpha=node_alpha, edgecolor=node_edgecolor, zorder=node_zorder, transform=ccrs.Geodetic()) if no_axis: ax = plt.gca() ax.set_axis_off() return plt
def plot_basin(gauge_id, dlat=0.05, dlon=0.1, tile_level=12): """ Plots location of gauge and surrounding territory. Args: gauge_id(int): The ID of the gauge to display dlat: Meridional extent of the map in degrees. dlon: Equatorial extent of the map in degrees. tile_level: The resolution level to use for the terrain in the background. """ if not gauge_id in gauge_ids: other = gauge_ids[np.argmin(np.abs(int(gauge_id) - gauge_ids))] raise ValueError("Gauge ID {} is not available from this dataset. The " "closest ID available is {}.".format(gauge_id, other)) try: from cartopy.io.img_tiles import Stamen from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter import cartopy.crs as ccrs lat = float(gauge_information.loc[gauge_information["gauge id"] == gauge_id]["latitude"]) lon = float(gauge_information.loc[gauge_information["gauge id"] == gauge_id]["longitude"]) tiler = Stamen("terrain") mercator = tiler.crs f = plt.figure(figsize = (8, 6)) gs = GridSpec(1, 1) ax = plt.subplot(gs[0], projection=mercator) lon_min = lon - dlon lon_max = lon + dlon lat_min = lat - dlat lat_max = lat + dlat ax.set_extent([lon_min, lon_max, lat_min, lat_max]) ax.add_image(tiler, tile_level) ax.set_xlabel("Longitude") ax.set_ylabel("Latitude") lon_min_r = np.round(lon - dlon, decimals=1) lon_max_r = np.round(lon + dlon, decimals=1) lat_min_r = np.round(lat - dlat, decimals=1) lat_max_r = np.round(lat + dlat, decimals=1) xticks = np.arange(lon_min, lon_max, 0.05) yticks = np.arange(lat_min, lat_max, 0.05) ax.set_xticks(xticks, crs=ccrs.PlateCarree()) ax.set_yticks(yticks, crs=ccrs.PlateCarree()) lon_formatter = LongitudeFormatter(zero_direction_label=True) lat_formatter = LatitudeFormatter() ax.xaxis.set_major_formatter(lon_formatter) ax.yaxis.set_major_formatter(lat_formatter) img=ax.scatter([lon], [lat], transform=ccrs.PlateCarree(), c="k", marker="x", s=50, label="Gauge location") ax.legend() except: url = "http://spfrnd.de/datasets/camels/plots/{}.png".format(gauge_id) img = plt.imread(url) plt.figure(figsize=(3,2), dpi=300) plt.imshow(img) plt.gca().set_axis_off()
def plot_trackline(lat, lon, raw_positions=None): """Maps longitude and latitude data. plot_trackline plots a series of lat/lons on a map. Args: lat (array): A numpy array of latitudinal data. lon (array): A numpy array of longitudinal data. raw_positions (array): A numpy array of raw position data. """ # Determine the min/max coordinates and place them in a list that will # contain our map boundaries. lat_bounds = [np.nanmin(lat), 0, np.nanmax(lat)] lon_bounds = [np.nanmin(lon), 0, np.nanmax(lon)] # Calculate the rest of the expanded boundaries and mid-lines. This may # or may not work well for your specific data. r = (lat_bounds[2] - lat_bounds[0]) / 2.0 lat_bounds[1] = lat_bounds[0] + r lat_bounds[0] = lat_bounds[0] - (r * (0.5 / r)) lat_bounds[2] = lat_bounds[2] + (r * (0.5 / r)) r = (lon_bounds[2] - lon_bounds[0]) / 2.0 lon_bounds[1] = lon_bounds[0] + r lon_bounds[0] = lon_bounds[0] - (r * (0.5 / r)) lon_bounds[2] = lon_bounds[2] + (r * (0.5 / r)) # Calculate the parallels and meridians parallels = np.arange(round(lat_bounds[0], 3), round(lat_bounds[2], 3), 0.5) meridians = np.arange(round(lon_bounds[0], 3), round(lon_bounds[2], 3), 0.5) # PLOTTING ON A MAP USING CARTOPY, EXAMPLE 1 # This example demonstrates using the stock_img() method to plot on a # standard image for the map (a downsampled version of the Natural Earth # shaded relief raster) # Create a map projection so we can plot this on a map ax = plt.axes(projection=ccrs.PlateCarree()) ax.stock_img() ax.coastlines(resolution='10m', color='black', linewidth=1) # Set the extent of the map ax.set_extent([lon_bounds[0], lon_bounds[2], lat_bounds[0], lat_bounds[2]], crs=ccrs.PlateCarree()) # Add gridlines to the map ax.gridlines(xlocs=meridians, ylocs=parallels, draw_labels=True) # Plot lon, lat values on the map plt.plot(lon, lat, color='r', marker='d', markerfacecolor='None', markeredgecolor='r') # If we've been given the raw positions, plot those as marks only. if raw_positions is not None: plt.plot(raw_positions[1], raw_positions[0], linestyle='None', color='b', marker='x') plt.show() # PLOTTING ON A MAP USING CARTOPY, EXAMPLE 2 # This example demonstrates how imagery from a tile providing web service # can be accessed for map plotting. # Create a map projection so we can plot this on a map tiler = Stamen('terrain-background') # image from http://maps.stamen.com/ mercator = tiler.crs ax1 = plt.axes(projection=mercator) ax1.add_image(tiler, 5) ax1.coastlines('10m') # Add gridlines to the map ax1.gridlines(draw_labels=True, xlocs=meridians, ylocs=parallels) # Plot lon, lat values on the map plt.plot(lon, lat, color='r', marker='d', markerfacecolor='None', markeredgecolor='r', transform=ccrs.PlateCarree()) # If we've been given the raw positions, plot those as marks only. if raw_positions is not None: plt.plot(raw_positions[1], raw_positions[0], linestyle='None', color='b', marker='x', transform=ccrs.PlateCarree()) plt.show()
import pandas as pd import matplotlib.pyplot as plt import cartopy.crs as ccrs from cartopy.io.img_tiles import Stamen #Rodzaj mapy z serwisu maps.stamen.com: Toner, Terrain #Smak (flavour) mapy: lite, bakgroudm, labels kafelki_podkładowe = Stamen('toner-lite') #kafelki_podkładowe = Stamen('terrain') uklad_wspolrzednych = kafelki_podkładowe.crs # Odwzorowanie walcowe równoodległościowe projekcjaKartograficzna = ccrs.PlateCarree() # Tworzenie rysunku Matplotlib, wymiary w calach fig = plt.figure(figsize=(10, 10), dpi=50) #dodajemy osie z prawej strony i u góry ax = fig.add_axes([0, 0, 1, 1], projection=kafelki_podkładowe.crs) #ustawiamy zakres -> kolejność argumentów (x_min, x_max, y_min, y_max) ax.set_extent([20.8, 21.13, 52.15, 52.3], crs=projekcjaKartograficzna) #dodajemy do mapy punkt o współrzędnych (20.9,52.2) ax.plot(20.9,52.2,linestyle='',markersize=9,\ marker='o', color='blue',transform=projekcjaKartograficzna) #dodajemy mapę podkładową #poziom szczegółowości 1-globalny, 14- poziom ulicy ax.add_image(kafelki_podkładowe, 13) plt.grid(True)