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_percen(irma_tc, exp, if_exp, axs): """ Plot irma damage in %. """ # south extent = [ exp.longitude.min() - BUFFER_DEG, exp.longitude.max() + BUFFER_DEG, exp.latitude.min() - BUFFER_DEG, exp.latitude.max() + BUFFER_DEG ] axs.set_extent((extent)) u_plot.add_shapes(axs) imp_irma = Impact() imp_irma.calc(exp, if_exp, irma_tc) imp_irma.eai_exp[exp.value > 0] = \ imp_irma.eai_exp[exp.value > 0]/exp.value[exp.value > 0]*100 imp_irma.eai_exp[exp.value == 0] = 0. sel_exp = imp_irma.eai_exp > 0 im = axs.hexbin(exp.longitude[sel_exp], exp.latitude[sel_exp], C=imp_irma.eai_exp[sel_exp], reduce_C_function=np.average, transform=ccrs.PlateCarree(), gridsize=2000, cmap='YlOrRd', vmin=0, vmax=50) axs.set_title('') axs.grid(False) scale_bar(axs, (0.90, 0.90), 10) return im
def plot_left(exp, data_irma, tc_irma, ax, scale_pos, cntour_loc, label_loc): """ Plot exposed value, irma track and irma wind field. """ extent = u_plot._get_borders(exp.coord) extent = ([extent[0] - BUFFER_DEG, extent[1] + BUFFER_DEG, extent[2] -\ BUFFER_DEG, extent[3] + BUFFER_DEG]) ax.set_extent((extent)) u_plot.add_shapes(ax) sel_pos = np.argwhere(exp.value > 0)[:, 0] ax.hexbin(exp.coord[sel_pos, 1], exp.coord[sel_pos, 0], C=exp.value[sel_pos], reduce_C_function=np.average, transform=ccrs.PlateCarree(), gridsize=2000, norm=LogNorm(vmin=MIN_VAL, vmax=MAX_VAL), cmap='YlOrRd', vmin=1.0e2, vmax=MAX_VAL) ax.set_title('') ax.grid(False) scale_bar(ax, scale_pos, 10) track = data_irma.data[0] ax.plot(track.lon.values, track.lat.values, linestyle='solid', transform=ccrs.PlateCarree(), lw=2, color='k') leg_lines = [ Line2D([0], [0], color='k', lw=2), Line2D([0], [0], color='grey', lw=1, ls=':') ] leg_names = ['Irma track', 'wind field (kn)'] if 'bbox' in label_loc: ax.legend(leg_lines, leg_names, bbox_to_anchor=label_loc['bbox'], loc=label_loc['loc']) else: ax.legend(leg_lines, leg_names, loc=label_loc['loc']) tc_irma.intensity *= MS2KN grid_x, grid_y = np.mgrid[tc_irma.centroids.coord[:, 1].min() : \ tc_irma.centroids.coord[:, 1].max() : complex(0, 2000), \ tc_irma.centroids.coord[:, 0].min() : \ tc_irma.centroids.coord[:, 0].max() : complex(0, 2000)] grid_im = griddata( (tc_irma.centroids.coord[:, 1], tc_irma.centroids.coord[:, 0]), np.array(tc_irma.intensity[0].todense()).squeeze(), (grid_x, grid_y)) cs = ax.contour(grid_x, grid_y, grid_im, linewidths=1.0, linestyles=':', \ levels=[60, 80, 100, 120], colors=['grey', 'grey', 'grey', 'grey', 'grey']) ax.clabel(cs, inline=1, fontsize=10, manual=cntour_loc, rotation=-20, fmt='%1.0f') tc_irma.intensity /= MS2KN
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_raster(self, res=None, raster_res=None, save_tiff=None, raster_f=lambda x: np.log10((np.fmax(x+1, 1))), label='value (log10)', **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 kwargs (optional): arguments for imshow matplotlib function Returns: matplotlib.figure.Figure, cartopy.mpl.geoaxes.GeoAxesSubplot """ if not 'geometry' in self.columns: self.set_geometry_points() crs_epsg, crs_unit = self._get_transformation() if not res: res= min(get_resolution(self.latitude.values, self.longitude.values)) if not raster_res: raster_res = res LOGGER.info('Raster from resolution %s%s to %s%s.', res, crs_unit, raster_res, crs_unit) exp_poly = self[['value']].set_geometry(self.buffer(res/2).envelope) # construct raster xmin, ymin, xmax, ymax = self.total_bounds rows, cols, ras_trans = points_to_raster((xmin, ymin, xmax, ymax), raster_res) raster = rasterize([(x, val) for (x, val) in zip(exp_poly.geometry, exp_poly.value)], out_shape=(rows, cols), transform=ras_trans, fill=0, all_touched=True, dtype=rasterio.float32, ) # save tiff if save_tiff is not None: ras_tiff = rasterio.open(save_tiff, 'w', driver='GTiff', \ height=raster.shape[0], width=raster.shape[1], count=1, \ dtype=np.float32, crs=self.crs, transform=ras_trans) ras_tiff.write(raster.astype(np.float32), 1) ras_tiff.close() # make plot fig, axis = u_plot.make_map(proj=crs_epsg) cbar_ax = fig.add_axes([0.99, 0.238, 0.03, 0.525]) fig.subplots_adjust(hspace=0, wspace=0) axis[0, 0].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[0, 0]) imag = axis[0, 0].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() posn = axis[0, 0].get_position() cbar_ax.set_position([posn.x0 + posn.width + 0.01, posn.y0, 0.04, posn.height]) return fig, axis
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: matplotlib.axes._subplots.AxesSubplot """ if not axis: _, axis = u_plot.make_map() u_plot.add_shapes(axis) if self.meta and not self.coord.size: self.set_meta_to_lat_lon() axis.scatter(self.lon, self.lat, **kwargs) return axis
def plot(self, **kwargs): """ Plot centroids scatter points over earth. Parameters: kwargs (optional): arguments for scatter matplotlib function Returns: matplotlib.figure.Figure, matplotlib.axes._subplots.AxesSubplot """ if 's' not in kwargs: kwargs['s'] = 1 fig, axis = u_plot.make_map() axis = axis[0][0] u_plot.add_shapes(axis) if self.meta and not self.coord.size: self.set_meta_to_lat_lon() axis.scatter(self.lon, self.lat, **kwargs) return fig, axis
def plot(self, **kwargs): """ Plot centroids points over earth. Parameters: kwargs (optional): arguments for scatter matplotlib function Returns: matplotlib.figure.Figure, matplotlib.axes._subplots.AxesSubplot """ if 's' not in kwargs: kwargs['s'] = 1 fig, axis = u_plot.make_map() axis = axis[0][0] u_plot.add_shapes(axis) axis.set_title(self.tag.join_file_names()) axis.scatter(self.lon, self.lat, **kwargs) return fig, axis
def plot_right(irma_tc, exp, ax, scale_pos, plot_line=False): """ Plot irma damage in USD. """ if_exp = ImpactFuncSet() if_em = IFTropCyclone() if_em.set_emanuel_usa() if_exp.append(if_em) imp_irma = Impact() imp_irma.calc(exp, if_exp, irma_tc) extent = [ exp.longitude.min() - BUFFER_DEG, exp.longitude.max() + BUFFER_DEG, exp.latitude.min() - BUFFER_DEG, exp.latitude.max() + BUFFER_DEG ] ax.set_extent((extent)) u_plot.add_shapes(ax) sel_pos = np.argwhere(imp_irma.eai_exp > 0)[:, 0] hex_bin = ax.hexbin(imp_irma.coord_exp[sel_pos, 1], imp_irma.coord_exp[sel_pos, 0], C=imp_irma.eai_exp[sel_pos], reduce_C_function=np.average, transform=ccrs.PlateCarree(), gridsize=2000, norm=LogNorm(vmin=MIN_VAL, vmax=MAX_VAL), cmap='YlOrRd', vmin=MIN_VAL, vmax=MAX_VAL) ax.set_title('') ax.grid(False) add_cntry_names(ax, extent) scale_bar(ax, scale_pos, 10) if plot_line: x1, y1 = [-64.57, -64.82], [18.28, 18.47] ax.plot(x1, y1, linewidth=1.0, color='grey', linestyle='--') return hex_bin
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_imp_map( self, run_datetime, title, cbar_label, polygon_file=None, polygon_file_crs="epsg:4326", proj=ccrs.PlateCarree(), figsize=(9, 13), adapt_fontsize=True, ): # select hazard with run_datetime # pylint: disable=protected-access if run_datetime is None: run_datetime = self.run_datetime[0] haz_ind = np.argwhere(np.isin(self.run_datetime, run_datetime))[0][0] # tryout new plot with right projection extend = "neither" value = self._impact[haz_ind].eai_exp # value[np.invert(mask)] = np.nan coord = self._impact[haz_ind].coord_exp # Generate array of values used in each subplot array_sub = value shapes = True if not polygon_file: shapes = False var_name = cbar_label geo_coord = coord num_im, list_arr = u_plot._get_collection_arrays(array_sub) list_tit = to_list(num_im, title, "title") list_name = to_list(num_im, var_name, "var_name") list_coord = to_list(num_im, geo_coord, "geo_coord") kwargs = dict() kwargs["cmap"] = CMAP_IMPACT kwargs["s"] = 5 kwargs["marker"] = "," kwargs["norm"] = BoundaryNorm( np.append( np.append([0], [10**x for x in np.arange(0, 2.9, 2.9 / 9)]), [10**x for x in np.arange(3, 7, 4 / 90)], ), CMAP_IMPACT.N, clip=True, ) # Generate each subplot fig, axis_sub, _fontsize = u_plot.make_map( num_im, proj=proj, figsize=figsize, adapt_fontsize=adapt_fontsize) if not isinstance(axis_sub, np.ndarray): axis_sub = np.array([[axis_sub]]) fig.set_size_inches(9, 8) for array_im, axis, tit, name, coord in zip(list_arr, axis_sub.flatten(), list_tit, list_name, list_coord): if coord.shape[0] != array_im.size: raise ValueError("Size mismatch in input array: %s != %s." % (coord.shape[0], array_im.size)) # Binned image with coastlines extent = u_plot._get_borders(coord) axis.set_extent((extent), ccrs.PlateCarree()) hex_bin = axis.scatter(coord[:, 1], coord[:, 0], c=array_im, transform=ccrs.PlateCarree(), **kwargs) if shapes: # add warning regions shp = shapereader.Reader(polygon_file) transformer = pyproj.Transformer.from_crs( polygon_file_crs, self._impact[haz_ind].crs, always_xy=True) for geometry, _ in zip(shp.geometries(), shp.records()): geom2 = shapely.ops.transform(transformer.transform, geometry) axis.add_geometries( [geom2], crs=ccrs.PlateCarree(), facecolor="none", edgecolor="gray", ) else: # add country boundaries u_plot.add_shapes(axis) # Create colorbar in this axis cbax = make_axes_locatable(axis).append_axes("bottom", size="6.5%", pad=0.3, axes_class=plt.Axes) cbar = plt.colorbar(hex_bin, cax=cbax, orientation="horizontal", extend=extend) cbar.set_label(name) cbar.formatter.set_scientific(False) cbar.set_ticks([0, 1000, 10000, 100000, 1000000]) cbar.set_ticklabels( ["0", "1 000", "10 000", "100 000", "1 000 000"]) title_position = { "model_text": [0.02, 0.85], "explain_text": [0.02, 0.81], "event_day": [0.98, 0.85], "run_start": [0.98, 0.81], } left_right = { "model_text": "left", "explain_text": "left", "event_day": "right", "run_start": "right", } color = { "model_text": "k", "explain_text": "k", "event_day": "r", "run_start": "k", } for t_i in tit: plt.figtext( title_position[t_i][0], title_position[t_i][1], tit[t_i], fontsize="xx-large", color=color[t_i], ha=left_right[t_i], ) fig.tight_layout() fig.subplots_adjust(top=0.8) return fig, axis_sub
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