def plot(self, axis=None, **kwargs): """Plot centroids scatter points over earth. Parameters ---------- axis : matplotlib.axes._subplots.AxesSubplot, optional axis to use kwargs : optional arguments for scatter matplotlib function Returns ------- axis : matplotlib.axes._subplots.AxesSubplot """ if self.meta and not self.coord.size: self.set_meta_to_lat_lon() pad = np.abs(u_coord.get_resolution(self.lat, self.lon)).min() proj_data, _ = u_plot.get_transformation(self.crs) proj_plot = proj_data if isinstance(proj_data, ccrs.PlateCarree): # use different projections for plot and data to shift the central lon in the plot xmin, ymin, xmax, ymax = u_coord.latlon_bounds(self.lat, self.lon, buffer=pad) proj_plot = ccrs.PlateCarree(central_longitude=0.5 * (xmin + xmax)) else: xmin, ymin, xmax, ymax = (self.lon.min() - pad, self.lat.min() - pad, self.lon.max() + pad, self.lat.max() + pad) if not axis: _, axis = u_plot.make_map(proj=proj_plot) axis.set_extent((xmin, xmax, ymin, ymax), crs=proj_data) u_plot.add_shapes(axis) axis.scatter(self.lon, self.lat, transform=proj_data, **kwargs) return axis
def plot_scatter(self, mask=None, ignore_zero=False, pop_name=True, buffer=0.0, extend='neither', axis=None, figsize=(9, 13), adapt_fontsize=True, **kwargs): """Plot exposures geometry's value sum scattered over Earth's map. The plot will we projected according to the current crs. Parameters: mask (np.array, optional): mask to apply to eai_exp plotted. ignore_zero (bool, optional): flag to indicate if zero and negative values are ignored in plot. Default: False pop_name : bool, optional add names of the populated places, by default True. buffer (float, optional): border to add to coordinates. Default: 0.0. extend (str, optional): extend border colorbar with arrows. [ 'neither' | 'both' | 'min' | 'max' ] axis (matplotlib.axes._subplots.AxesSubplot, optional): axis to use figsize (tuple, optional): figure size for plt.subplots adapt_fontsize : bool, optional If set to true, the size of the fonts will be adapted to the size of the figure. Otherwise the default matplotlib font size is used. Default is True. kwargs (optional): arguments for scatter matplotlib function, e.g. cmap='Greys'. Default: 'Wistia' Returns: cartopy.mpl.geoaxes.GeoAxesSubplot """ crs_epsg, _ = u_plot.get_transformation(self.crs) title = self.tag.description cbar_label = 'Value (%s)' % self.value_unit if mask is None: mask = np.ones((self.gdf.shape[0], ), dtype=bool) if ignore_zero: pos_vals = self.gdf.value[mask].values > 0 else: pos_vals = np.ones((self.gdf.value[mask].values.size, ), dtype=bool) value = self.gdf.value[mask][pos_vals].values coord = np.stack([ self.gdf.latitude[mask][pos_vals].values, self.gdf.longitude[mask][pos_vals].values ], axis=1) return u_plot.geo_scatter_from_array(value, coord, cbar_label, title, pop_name, buffer, extend, proj=crs_epsg, axes=axis, figsize=figsize, adapt_fontsize=adapt_fontsize, **kwargs)
def plot_raster(self, res=None, raster_res=None, save_tiff=None, raster_f=lambda x: np.log10((np.fmax(x+1, 1))), label='value (log10)', scheduler=None, axis=None, **kwargs): """ Generate raster from points geometry and plot it using log10 scale: np.log10((np.fmax(raster+1, 1))). Parameters: res (float, optional): resolution of current data in units of latitude and longitude, approximated if not provided. raster_res (float, optional): desired resolution of the raster save_tiff (str, optional): file name to save the raster in tiff format, if provided raster_f (lambda function): transformation to use to data. Default: log10 adding 1. label (str): colorbar label scheduler (str): used for dask map_partitions. “threads”, “synchronous” or “processes” axis (matplotlib.axes._subplots.AxesSubplot, optional): axis to use kwargs (optional): arguments for imshow matplotlib function Returns: matplotlib.figure.Figure, cartopy.mpl.geoaxes.GeoAxesSubplot """ if self.meta and self.meta['height']*self.meta['width'] == len(self): raster = self.value.values.reshape((self.meta['height'], self.meta['width'])) # check raster starts by upper left corner if self.latitude.values[0] < self.latitude.values[-1]: raster = np.flip(raster, axis=0) if self.longitude.values[0] > self.longitude.values[-1]: LOGGER.error('Points are not ordered according to meta raster.') raise ValueError else: raster, meta = co.points_to_raster(self, ['value'], res, raster_res, scheduler) raster = raster.reshape((meta['height'], meta['width'])) # save tiff if save_tiff is not None: ras_tiff = rasterio.open(save_tiff, 'w', driver='GTiff', \ height=meta['height'], width=meta['width'], count=1, \ dtype=np.float32, crs=self.crs, transform=meta['transform']) ras_tiff.write(raster.astype(np.float32), 1) ras_tiff.close() # make plot crs_epsg, _ = u_plot.get_transformation(self.crs) xmin, ymin, xmax, ymax = self.longitude.min(), self.latitude.min(), \ self.longitude.max(), self.latitude.max() if not axis: _, axis = u_plot.make_map(proj=crs_epsg) cbar_ax = make_axes_locatable(axis).append_axes('right', size="6.5%", \ pad=0.1, axes_class=plt.Axes) axis.set_extent([max(xmin, crs_epsg.x_limits[0]), \ min(xmax, crs_epsg.x_limits[1]), max(ymin, crs_epsg.y_limits[0]), \ min(ymax, crs_epsg.y_limits[1])], crs_epsg) u_plot.add_shapes(axis) imag = axis.imshow(raster_f(raster), **kwargs, origin='upper', extent=[xmin, xmax, ymin, ymax], transform=crs_epsg) plt.colorbar(imag, cax=cbar_ax, label=label) plt.draw() return axis
def plot_hexbin(self, mask=None, ignore_zero=False, pop_name=True, buffer=0.0, extend='neither', axis=None, figsize=(9, 13), **kwargs): """Plot exposures geometry's value sum binned over Earth's map. An other function for the bins can be set through the key reduce_C_function. The plot will we projected according to the current crs. Parameters: mask (np.array, optional): mask to apply to eai_exp plotted. ignore_zero (bool, optional): flag to indicate if zero and negative values are ignored in plot. Default: False pop_name (bool, optional): add names of the populated places buffer (float, optional): border to add to coordinates. Default: 0.0. extend (str, optional): extend border colorbar with arrows. [ 'neither' | 'both' | 'min' | 'max' ] axis (matplotlib.axes._subplots.AxesSubplot, optional): axis to use figsize (tuple): figure size for plt.subplots kwargs (optional): arguments for hexbin matplotlib function, e.g. reduce_C_function=np.average. Default: reduce_C_function=np.sum Returns: cartopy.mpl.geoaxes.GeoAxesSubplot """ crs_epsg, _ = u_plot.get_transformation(self.crs) title = self.tag.description cbar_label = 'Value (%s)' % self.value_unit if 'reduce_C_function' not in kwargs: kwargs['reduce_C_function'] = np.sum if mask is None: mask = np.ones((self.gdf.shape[0], ), dtype=bool) if ignore_zero: pos_vals = self.gdf.value[mask].values > 0 else: pos_vals = np.ones((self.gdf.value[mask].values.size, ), dtype=bool) value = self.gdf.value[mask][pos_vals].values coord = np.stack([ self.gdf.latitude[mask][pos_vals].values, self.gdf.longitude[mask][pos_vals].values ], axis=1) return u_plot.geo_bin_from_array(value, coord, cbar_label, title, pop_name, buffer, extend, proj=crs_epsg, axes=axis, figsize=figsize, **kwargs)
def test_get_transform_3035_pass(self): """ Check that assigned attribute is correctly set.""" res, unit = u_plot.get_transformation({'init': 'epsg:3035'}) self.assertIsInstance(res, cartopy._epsg._EPSGProjection) self.assertEqual(unit, 'm')
def test_get_transform_3395_pass(self): """ Check that assigned attribute is correctly set.""" res, unit = u_plot.get_transformation({'init': 'epsg:3395'}) self.assertIsInstance(res, cartopy.crs.Mercator) self.assertEqual(unit, 'm')
def test_get_transform_4326_pass(self): """ Check _get_transformation for 4326 epsg.""" res, unit = u_plot.get_transformation({'init': 'epsg:4326'}) self.assertIsInstance(res, cartopy.crs.PlateCarree) self.assertEqual(unit, '°')
def test_get_transform_3035_pass(self): """Check that assigned attribute is correctly set.""" res, unit = u_plot.get_transformation('epsg:3035') self.assertIsInstance(res, cartopy.crs.Projection) self.assertEqual(res.epsg_code, 3035) self.assertEqual(unit, 'm')
def plot_raster(self, res=None, raster_res=None, save_tiff=None, raster_f=lambda x: np.log10((np.fmax(x + 1, 1))), label='value (log10)', scheduler=None, axis=None, figsize=(9, 13), **kwargs): """Generate raster from points geometry and plot it using log10 scale: np.log10((np.fmax(raster+1, 1))). Parameters: res (float, optional): resolution of current data in units of latitude and longitude, approximated if not provided. raster_res (float, optional): desired resolution of the raster save_tiff (str, optional): file name to save the raster in tiff format, if provided raster_f (lambda function): transformation to use to data. Default: log10 adding 1. label (str): colorbar label scheduler (str): used for dask map_partitions. “threads”, “synchronous” or “processes” axis (matplotlib.axes._subplots.AxesSubplot, optional): axis to use figsize (tuple, optional): figure size for plt.subplots kwargs (optional): arguments for imshow matplotlib function Returns: matplotlib.figure.Figure, cartopy.mpl.geoaxes.GeoAxesSubplot """ if self.meta and self.meta.get('height', 0) * self.meta.get( 'height', 0) == len(self.gdf): raster = self.gdf.value.values.reshape( (self.meta['height'], self.meta['width'])) # check raster starts by upper left corner if self.gdf.latitude.values[0] < self.gdf.latitude.values[-1]: raster = np.flip(raster, axis=0) if self.gdf.longitude.values[0] > self.gdf.longitude.values[-1]: LOGGER.error( 'Points are not ordered according to meta raster.') raise ValueError else: raster, meta = u_coord.points_to_raster(self.gdf, ['value'], res, raster_res, scheduler) raster = raster.reshape((meta['height'], meta['width'])) # save tiff if save_tiff is not None: with rasterio.open(save_tiff, 'w', driver='GTiff', height=meta['height'], width=meta['width'], count=1, dtype=np.float32, crs=self.crs, transform=meta['transform']) as ras_tiff: ras_tiff.write(raster.astype(np.float32), 1) # make plot proj_data, _ = u_plot.get_transformation(self.crs) proj_plot = proj_data if isinstance(proj_data, ccrs.PlateCarree): # use different projections for plot and data to shift the central lon in the plot xmin, ymin, xmax, ymax = u_coord.latlon_bounds( self.gdf.latitude.values, self.gdf.longitude.values) proj_plot = ccrs.PlateCarree(central_longitude=0.5 * (xmin + xmax)) else: xmin, ymin, xmax, ymax = (self.gdf.longitude.min(), self.gdf.latitude.min(), self.gdf.longitude.max(), self.gdf.latitude.max()) if not axis: _, axis = u_plot.make_map(proj=proj_plot, figsize=figsize) cbar_ax = make_axes_locatable(axis).append_axes('right', size="6.5%", pad=0.1, axes_class=plt.Axes) axis.set_extent((xmin, xmax, ymin, ymax), crs=proj_data) u_plot.add_shapes(axis) imag = axis.imshow(raster_f(raster), **kwargs, origin='upper', extent=(xmin, xmax, ymin, ymax), transform=proj_data) plt.colorbar(imag, cax=cbar_ax, label=label) plt.draw() return axis
def plot_raster(self, res=None, raster_res=None, save_tiff=None, raster_f=lambda x: np.log10((np.fmax(x + 1, 1))), label='value (log10)', scheduler=None, axis=None, figsize=(9, 13), fill=True, adapt_fontsize=True, **kwargs): """Generate raster from points geometry and plot it using log10 scale: np.log10((np.fmax(raster+1, 1))). Parameters ---------- res : float, optional resolution of current data in units of latitude and longitude, approximated if not provided. raster_res : float, optional desired resolution of the raster save_tiff : str, optional file name to save the raster in tiff format, if provided raster_f : lambda function transformation to use to data. Default: log10 adding 1. label : str colorbar label scheduler : str used for dask map_partitions. “threads”, “synchronous” or “processes” axis : matplotlib.axes._subplots.AxesSubplot, optional axis to use figsize : tuple, optional figure size for plt.subplots fill : bool, optional If false, the areas with no data will be plotted in white. If True, the areas with missing values are filled as 0s. The default is True. adapt_fontsize : bool, optional If set to true, the size of the fonts will be adapted to the size of the figure. Otherwise the default matplotlib font size is used. Default is True. kwargs : optional arguments for imshow matplotlib function Returns ------- matplotlib.figure.Figure, cartopy.mpl.geoaxes.GeoAxesSubplot """ if self.meta and self.meta.get('height', 0) * self.meta.get( 'height', 0) == len(self.gdf): raster = self.gdf.value.values.reshape( (self.meta['height'], self.meta['width'])) # check raster starts by upper left corner if self.gdf.latitude.values[0] < self.gdf.latitude.values[-1]: raster = np.flip(raster, axis=0) if self.gdf.longitude.values[0] > self.gdf.longitude.values[-1]: raise ValueError( 'Points are not ordered according to meta raster.') else: raster, meta = u_coord.points_to_raster(self.gdf, ['value'], res, raster_res, scheduler) raster = raster.reshape((meta['height'], meta['width'])) # save tiff if save_tiff is not None: with rasterio.open(save_tiff, 'w', driver='GTiff', height=meta['height'], width=meta['width'], count=1, dtype=np.float32, crs=self.crs, transform=meta['transform']) as ras_tiff: ras_tiff.write(raster.astype(np.float32), 1) # make plot proj_data, _ = u_plot.get_transformation(self.crs) proj_plot = proj_data if isinstance(proj_data, ccrs.PlateCarree): # use different projections for plot and data to shift the central lon in the plot xmin, ymin, xmax, ymax = u_coord.latlon_bounds( self.gdf.latitude.values, self.gdf.longitude.values) proj_plot = ccrs.PlateCarree(central_longitude=0.5 * (xmin + xmax)) else: xmin, ymin, xmax, ymax = (self.gdf.longitude.min(), self.gdf.latitude.min(), self.gdf.longitude.max(), self.gdf.latitude.max()) if not axis: _, axis, fontsize = u_plot.make_map(proj=proj_plot, figsize=figsize, adapt_fontsize=adapt_fontsize) else: fontsize = None cbar_ax = make_axes_locatable(axis).append_axes('right', size="6.5%", pad=0.1, axes_class=plt.Axes) axis.set_extent((xmin, xmax, ymin, ymax), crs=proj_data) u_plot.add_shapes(axis) if not fill: raster = np.where(raster == 0, np.nan, raster) raster_f = lambda x: np.log10((np.maximum(x + 1, 1))) if 'cmap' not in kwargs: kwargs['cmap'] = CMAP_RASTER imag = axis.imshow(raster_f(raster), **kwargs, origin='upper', extent=(xmin, xmax, ymin, ymax), transform=proj_data) cbar = plt.colorbar(imag, cax=cbar_ax, label=label) plt.colorbar(imag, cax=cbar_ax, label=label) plt.tight_layout() plt.draw() if fontsize: cbar.ax.tick_params(labelsize=fontsize) cbar.ax.yaxis.get_offset_text().set_fontsize(fontsize) for item in [axis.title, cbar.ax.xaxis.label, cbar.ax.yaxis.label]: item.set_fontsize(fontsize) return axis