def contour_transition(da_transition: xr.DataArray, ax: mpl.axes.Axes, rcp: str): """Takes in DataArray for transition time from x to y months Omega Aragonite undersaturation, axes for the plot, and the simulation name, and makes a contour plot.""" crs = ccrs.Robinson(central_longitude=180) src = ccrs.PlateCarree() clevs = np.arange(0, 31, 5) lon = da_transition.xt_ocean.data lat = da_transition.yt_ocean.data im = ax.contourf(lon, lat, da_transition, cmap='plasma', levels=clevs, transform=src, robust=True) if ax == plt.gcf().get_axes()[0]: cbar = plt.colorbar(im, ax=plt.gcf().get_axes(), orientation='horizontal', fraction=0.05, pad=0.05) cbar.set_label( 'Transition Time from 1-->6 Months Undersaturated (years)', fontsize=16) ax.add_feature(cfeature.LAND, zorder=10, facecolor='darkgray') ax.set_global() ax.set_title(rcp)
def kde2d(X: Union[np.ndarray, Series, List, Tuple], Y: Union[np.ndarray, Series, List, Tuple], c: str = "red", ax: mpl.axes.Axes = None, fill: bool = False, with_scatter: bool = False, **contour_kwargs): """TODO: Generates a 2D KDE using contours.""" instance_check((X, Y), (list, tuple, np.ndarray, Series)) instance_check(c, str) instance_check((fill, with_scatter), bool) instance_check(ax, mpl.axes.Axes) arrays_equal_size(X, Y) # calculate density _X, _Y = remove_na(np.asarray(X), np.asarray(Y), paired=True) H = density(_X, _Y) offx = np.abs(_X.max() - _X.min()) / 15.0 offy = np.abs(_Y.max() - _Y.min()) / 15.0 _alpha = 0.5 if with_scatter else 1.0 if ax is None: fig, ax = plt.subplots(figsize=(8, 5)) if fill: ax.contourf( H, extent=(_X.min() - offx, _X.max() + offx, _Y.min() - offy, _Y.max() + offy), color=c, alpha=_alpha, ) else: cset = ax.contour(H, extent=(_X.min() - offx, _X.max() + offx, _Y.min() - offy, _Y.max() + offy), color=c, **contour_kwargs) ax.clabel(cset, inline=1, fontsize=10) if with_scatter: ax.scatter(_X, _Y, c=c, alpha=_alpha) return ax
def draw_3d_plot(ax: mpl.axes.Axes, x: np.ndarray, y: np.ndarray, z: np.ndarray, plot_type: str, marker: str = 'X', marker_size: int = 50, marker_color: str = 'red', interpolation: str = 'linear', cmap: str = 'viridis') -> None: '''Draw a 3d plot. See XYZData class for explanation of arguments >>> points = np.random.rand(1000, 2) >>> x = np.random.rand(10) >>> y = np.random.rand(10) >>> z = x ** 2 + y ** 2 >>> if has_display(): ... fig, ax = plt.subplots() ... draw_3d_plot(ax, x = x, y = y, z = z, plot_type = 'contour', interpolation = 'linear') ''' xi = np.linspace(min(x), max(x)) yi = np.linspace(min(y), max(y)) X, Y = np.meshgrid(xi, yi) Z = griddata((x, y), z, (xi[None, :], yi[:, None]), method=interpolation) Z = np.nan_to_num(Z) if plot_type == 'surface': ax.plot_surface(X, Y, Z, cmap=cmap) if marker is not None: ax.scatter(x, y, z, marker=marker, s=marker_size, c=marker_color) elif plot_type == 'contour': cs = ax.contour(X, Y, Z, linewidths=0.5, colors='k') ax.clabel(cs, cs.levels[::2], fmt="%.3g", inline=1) ax.contourf(X, Y, Z, cmap=cmap) if marker is not None: ax.scatter(x, y, marker=marker, s=marker_size, c=marker_color, zorder=10) else: raise Exception(f'unknown plot type: {plot_type}') m = cm.ScalarMappable(cmap=cmap) m.set_array(Z) plt.colorbar(m, ax=ax)
def _do_contour(self, a: mpl.axes.Axes, x: np.ndarray, y: np.ndarray, n_levels: int): """Create density contour plot Parameters ---------- a Axes to draw on x, y data n_levels Number of contour levels """ contour_grid = np.array( np.meshgrid(np.linspace(*self._bounds[0], 100), np.linspace(*self._bounds[1], 100))) contour_grid_flat = np.reshape(contour_grid, (2, -1)) a.contourf(*contour_grid, self._calc_kde(x, y, *contour_grid_flat).reshape( contour_grid.shape[1:]), cmap=mpl.cm.get_cmap("viridis", n_levels), levels=n_levels)
def contour_temp(ds: xr.core.dataset.Dataset, in_year: int, ax: mpl.axes.Axes, title: str, central_longitude: int = 0) -> mpl.axes.Axes: """Takes in a Dataset for Temperature, and creates a contour plot for the data for the given year. Adds a darkgrey landmask, grindlines, coastlines, a title, and a colorbar to the plot.""" clevs = np.arange(260, 320, 10) # Can also choose to define colormap colors = ['blue', 'green', 'yellow', 'orange', 'red'] crs = ccrs.PlateCarree(central_longitude=central_longitude) # Specify variables X = ds['xt_ocean'] Y = ds['yt_ocean'] # Already grouped by year Z = ds['temp'].sel(year=in_year).squeeze() Z, X = add_cyclic_point(Z, coord=X) # can also use cmap='plasma','inferno',etc... im = ax.contourf(X, Y, Z, levels=clevs, transform=crs) if ax == plt.gcf().get_axes()[0]: cbar = plt.colorbar(im, ax=plt.gcf().get_axes(), orientation='horizontal', fraction=0.05, pad=0.05) cbar.set_label('Temeprature ($^\circ\,K$)', fontsize=18) # Zoom in on a region # ax.set_extent([x0,x1,y0,y1]) # Add land mask, gridlines, coastlines, and title ax.add_feature(cfeature.LAND, zorder=10, facecolor='darkgray') ax.gridlines() ax.coastlines() ax.set_title(title + " " + str(in_year), fontsize=18, loc='center') return ax
def contour_oa(ds: xr.core.dataset.Dataset, in_year: int, ax: mpl.axes.Axes, title: str, central_longitude: int = 0) -> mpl.axes.Axes: """Takes in a Dataset for Omega Aragonite, and creates a contour plot for the data for the given year. Adds a darkgrey landmask, grindlines, coastlines, a title, and a colorbar to the plot.""" clevs = np.array([0, 1, 2, 3, 4]) # Can also choose to define colormap # colors = ['red', 'orange', 'yellow','green','blue'] crs = ccrs.PlateCarree(central_longitude=central_longitude) # Specify variables X = ds['XT_OCEAN'] Y = ds['YT_OCEAN'] # Already grouped by year Z = ds['OMEGA_ARAG'].sel(year=in_year).squeeze() Z, X = add_cyclic_point(Z, coord=X) im = ax.contourf(X, Y, Z, clevs, transform=crs) if ax == plt.gcf().get_axes()[0]: cbar = plt.colorbar(im, ax=plt.gcf().get_axes(), orientation='horizontal', fraction=0.05, pad=0.05) cbar.set_label('$\Omega$ Aragonite', fontsize=18) # Zoom in on a region # ax.set_extent([x0,x1,y0,y1]) # Add land mask, gridlines, coastlines, and title ax.add_feature(cfeature.LAND, zorder=10, facecolor='darkgray') ax.gridlines() ax.coastlines() ax.set_title(title + " " + str(in_year), fontsize=18, loc='center') return ax
def contour_emergence(da_emergence: xr.DataArray, m: int, ax: mpl.axes.Axes, rcp: str = None): """Takes in DataArray for time of emergence, axes for the plot, number of undersaturation months for recognized signal, and simulation name, and makes a contour plot.""" crs = ccrs.Robinson(central_longitude=180) src = ccrs.PlateCarree() clevs = np.arange(1950, 2101, 10) lon = da_emergence.xt_ocean.data lat = da_emergence.yt_ocean.data im = ax.contourf(lon, lat, da_emergence, cmap='plasma', levels=clevs, transform=src, robust=True) if ax == plt.gcf().get_axes()[0]: cbar = plt.colorbar(im, ax=plt.gcf().get_axes(), orientation='horizontal', fraction=0.05, pad=0.05) cbar.set_label('Year of Emergence', fontsize=16) ax.add_feature(cfeature.LAND, zorder=10, facecolor='darkgray') ax.set_global() if m == 1: months = 'month' else: months = 'months' if rcp == None: ax.set_title(str(m) + ' ' + months + '/year', fontsize=16) else: ax.set_title(rcp + ' - ' + str(m) + ' ' + months + '/year', fontsize=16)
def draw_3d_plot(ax: mpl.axes.Axes, x: np.ndarray, y: np.ndarray, z: np.ndarray, plot_type: str = 'contour', marker: str = 'X', marker_size: int = 50, marker_color: str = 'red', interpolation: str = 'linear', cmap: matplotlib.colors.Colormap = matplotlib.cm.RdBu_r, min_level: float = math.nan, max_level: float = math.nan) -> None: '''Draw a 3d plot. See XYZData class for explanation of arguments >>> points = np.random.rand(1000, 2) >>> x = np.random.rand(10) >>> y = np.random.rand(10) >>> z = x ** 2 + y ** 2 >>> if has_display(): ... fig, ax = plt.subplots() ... draw_3d_plot(ax, x = x, y = y, z = z, plot_type = 'contour', interpolation = 'linear'); ''' xi = np.linspace(min(x), max(x)) yi = np.linspace(min(y), max(y)) X, Y = np.meshgrid(xi, yi) Z = griddata((x, y), z, (xi[None, :], yi[:, None]), method=interpolation) Z = np.nan_to_num(Z) if plot_type == 'surface': ax.plot_surface(X, Y, Z, cmap=cmap) if marker is not None: ax.scatter(x, y, z, marker=marker, s=marker_size, c=marker_color) m = cm.ScalarMappable(cmap=cmap) m.set_array(Z) plt.colorbar(m, ax=ax) elif plot_type == 'contour': # extract all colors from the map cmaplist = [cmap(i) for i in range(cmap.N)] # create the new map cmap = cmap.from_list('Custom cmap', cmaplist, cmap.N) Z = np.ma.masked_array(Z, mask=~np.isfinite(Z)) if math.isnan(min_level): min_level = np.min(Z) if math.isnan(max_level): max_level = np.max(Z) # define the bins and normalize and forcing 0 to be part of the colorbar! bounds = np.arange(min_level, max_level, (max_level - min_level) / cmap.N) idx = np.searchsorted(bounds, 0) bounds = np.insert(bounds, idx, 0) norm = BoundaryNorm(bounds, cmap.N) cs = ax.contourf(X, Y, Z, cmap=cmap, norm=norm) if marker is not None: x = x[np.isfinite(z)] y = y[np.isfinite(z)] ax.scatter(x, y, marker=marker, s=marker_size, c=z[np.isfinite(z)], zorder=10, cmap=cmap) LABEL_SIZE = 16 ax.tick_params(axis='both', which='major', labelsize=LABEL_SIZE) ax.tick_params(axis='both', which='minor', labelsize=LABEL_SIZE) cbar = plt.colorbar(cs, ax=ax) cbar.ax.tick_params(labelsize=LABEL_SIZE) else: raise Exception(f'unknown plot type: {plot_type}')