def one_panel_plot(surfdat_1, tit1, t_cmap, xsize, ysize, v_min1, v_max1, cl1, bigtit): "TESTED" from salishsea_tools import (teos_tools, tidetools, viz_tools) import matplotlib.pyplot as plt import cmocean as cm import numpy as np fig, ax = plt.subplots(1, 1, figsize=(xsize, ysize), sharey=True) cmap = t_cmap tplt = np.ma.masked_values(surfdat_1, 0) ax.set_title(tit1) v_min = v_min1 v_max = v_max1 clabel = cl1 viz_tools.set_aspect(ax) mesh = ax.pcolormesh(tplt, cmap=t_cmap, vmin=v_min, vmax=v_max) cbar = fig.colorbar(mesh, ax=ax) cbar.set_label(clabel) ax.set_xlabel('x Index') ax.set_ylabel('y Index') cmap.set_bad('slategray') plt.suptitle(bigtit, fontsize=20)
def one_panel_plot(surfdat_1, stns, tit1,t_cmap,xsize,ysize,v_min1,v_max1,cl1,bigtit): "TESTED" fig, ax = plt.subplots(1, 1, figsize=(xsize, ysize), sharey=True) cmap = t_cmap tplt = np.ma.masked_values(surfdat_1,0) ax.set_title(tit1,fontsize = 20 ) v_min = v_min1 v_max = v_max1 clabel = cl1 viz_tools.set_aspect(ax) mesh = ax.pcolormesh(tplt, cmap=t_cmap, vmin=v_min, vmax=v_max) cbar = fig.colorbar(mesh, ax=ax) cbar.set_label(clabel, fontsize = 20 ) cbar.ax.tick_params(labelsize=20) ax.set_xlabel('x Index', fontsize = 20 ) ax.set_ylabel('y Index', fontsize = 20 ) for key in stns: tx = stns[key]['x'] ty = stns[key]['y'] col = stns[key]['color'] code = stns[key]['code'] pat = patches.Rectangle((tx,ty),20,20,linewidth=2,edgecolor=col,facecolor='none') ax.add_patch(pat) ax.text(tx+22,ty+3,code, weight = 'bold', fontsize = 20) plt.xticks(fontsize=14) plt.yticks(fontsize=14) cmap.set_bad('aliceblue') plt.suptitle(bigtit,fontsize=20)
def clusters_basic(ax1,year,var,noclust,cl_this, colors, legend = True, markersize = 20, legfontsize = 12 ): import pickle import numpy as np import cmocean as cm import sys sys.path.append('./extraction_scripts') import map_fxn as mf from salishsea_tools import ( viz_tools) bath = '/results/nowcast-sys/NEMO-forcing/grid/mesh_mask_SalishSea2.nc' grid = mf.import_bathy(bath) tpkl = f'./pkls/{var}_clustmat_{year}.pkl' cl = pickle.load(open(tpkl, 'rb')) viz_tools.set_aspect(ax1) fmask = (grid.fmask[0,0,:,:]) mesh = ax1.pcolormesh(fmask, vmin=0, vmax=1, cmap = cm.cm.deep) ax1.set_ylim([0,898]) ax1.set_xlim([0,398]) stn_x, stn_y = mf.make_stns(10) d_stn_x, d_stn_y = mf.filter_stn_in_domain(stn_x,stn_y,fmask) d_stn_xar = np.array(d_stn_x) d_stn_yar = np.array(d_stn_y) edge = np.where((d_stn_xar<=10) | (d_stn_yar>=888)) np.squeeze(edge) np.shape(edge) edgear = np.array(edge) edgear = edgear[0] d_stn_xar =np.delete(d_stn_xar,edge) d_stn_yar = np.delete(d_stn_yar,edge) for j in range(1,noclust+1): cluster = np.where(cl_this == j) cluster = np.squeeze(cluster) c1_x = np.take(d_stn_xar,cluster) c1_y = np.take(d_stn_yar,cluster) pts = ax1.scatter(c1_x,c1_y,s=markersize,c=colors[j], label=str(j), marker='o') ax1.set_xticklabels( () ) ax1.set_yticklabels( () ) tit = 'year ' + year # + ' \n n. clusters = '+ str(noclust) if legend: ax1.legend(bbox_to_anchor=(1.06, 1), fontsize = legfontsize) ax1.set_title(tit,fontsize = legfontsize + 2)
def make_plot(i): ax.clear() viz_tools.set_aspect(ax) cmap = t_cmap tplt = hrly_dat[i, :, :] tplt = np.ma.masked_values(tplt, 0) mesh = ax.pcolormesh(tplt, cmap=t_cmap, vmin=v_min, vmax=v_max) t_cmap.set_bad('slategray') ax.set_title(tit + ', hour = ' + str(i + 1)) #ax.colorbar(mesh) #fig.colorbar(mesh, ax=ax) return ax, mesh
def phpco2om_plot(surfdat_1, surfdat_2, surfdat_3, tit1, tit2, tit3, t_cmap1, t_cmap2, t_cmap3, xsize, ysize, v_min1, v_max1, v_min2, v_max2, v_min3, v_max3, cl1, cl2, cl3, bigtit, dirstr, ind): "TESTED" from salishsea_tools import (teos_tools, tidetools, viz_tools) import matplotlib.pyplot as plt import cmocean as cm import numpy as np fig, axs = plt.subplots(1, 3, figsize=(xsize, ysize), sharey=True) time_steps = (0, 1, 2) for ax, t in zip(axs, time_steps): if t == 0: tplt = np.ma.masked_values(surfdat_1, 0) ax.set_title(tit1) v_min = v_min1 v_max = v_max1 t_cmap = t_cmap1 clabel = cl1 if t == 1: tplt = np.ma.masked_values(surfdat_2, 0) ax.set_title(tit2) v_min = v_min2 v_max = v_max2 t_cmap = t_cmap2 clabel = cl2 if t == 2: tplt = np.ma.masked_values(surfdat_3, 0) ax.set_title(tit3) v_min = v_min3 v_max = v_max3 t_cmap = t_cmap3 clabel = cl3 viz_tools.set_aspect(ax) mesh = ax.pcolormesh(tplt, cmap=t_cmap, vmin=v_min, vmax=v_max) cbar = fig.colorbar(mesh, ax=ax) cbar.set_label(clabel) ax.set_xlabel('x Index') axs[0].set_ylabel('y Index') t_cmap.set_bad('slategray') plt.suptitle(bigtit, fontsize=20) figtit = 'CCpar_day_' + str(ind) total_fig = dirstr + figtit + '.png' fig.savefig(total_fig) plt.close(fig)
def test_set_aspect_map_lats(self): axes = Mock() lats = np.array([42.0]) lats_aspect = 1 / np.cos(42 * np.pi / 180) aspect = viz_tools.set_aspect(axes, coords='map', lats=lats) axes.set_aspect.assert_called_once_with(lats_aspect, adjustable='box') assert aspect == lats_aspect
def _surface_axes_labels( ax, tracer_var, depth_integrated, clevels, cbar, theme ): cbar_units = ( f'{tracer_var.units}*m' if depth_integrated else f'{tracer_var.units}') cbar_label = f'{tracer_var.long_name} [{cbar_units}]' _cbar_labels(cbar, clevels[::2], theme, cbar_label) ax.set_xlabel( 'Grid x', color=theme.COLOURS['text']['axis'], fontproperties=theme.FONTS['axis']) ax.set_ylabel( 'Grid y', color=theme.COLOURS['text']['axis'], fontproperties=theme.FONTS['axis']) ax.set_axis_bgcolor('burlywood') viz_tools.set_aspect(ax) theme.set_axis_colors(ax)
def _prep_fig_axes(figsize, theme, sections=(450, ), pos=((0.1, 0.95), )): # Make Figure fig = plt.figure(figsize=figsize, facecolor=theme.COLOURS["figure"]["facecolor"]) # Make Sections ax_section = {} for index, section in enumerate(zip(sections, pos)): gs = gridspec.GridSpec(2, 1, height_ratios=[1, 2]) gs.update(bottom=section[1][0], top=section[1][1], left=0.1, right=0.5, hspace=0.05) ax_section[str( section[0])] = [fig.add_subplot(gs[0]), fig.add_subplot(gs[1])] for ax, shift, axis in zip(ax_section[str(section[0])], [0, 1], ["bottom", "top"]): ax.spines[axis].set_visible(False) ax.tick_params(which="both", top=False, right=False, direction="out") ax.set_facecolor(theme.COLOURS["axes"]["background"]) theme.set_axis_colors(ax) ax_section[str(section[0])][0].tick_params(which="both", labelbottom=False, bottom=False) # Make Surface gs = gridspec.GridSpec(1, 1) gs.update(bottom=0.1, top=0.95, left=0.55, right=0.9) ax_surface = fig.add_subplot(gs[0]) viz_tools.set_aspect(ax_surface) theme.set_axis_colors(ax_surface) # Make Colorbar gs = gridspec.GridSpec(1, 1) gs.update(bottom=0.03, top=0.04, left=0.1, right=0.5) ax_cbar = fig.add_subplot(gs[0]) theme.set_axis_colors(ax_cbar) return fig, (ax_section, ax_surface, ax_cbar)
def _surface_axes_labels(ax, tracer_var, depth_integrated, clevels, cbar, theme): cbar_units = f"{tracer_var.units}*m" if depth_integrated else f"{tracer_var.units}" cbar_label = f"{tracer_var.long_name} [{cbar_units}]" _cbar_labels(cbar, clevels[::2], theme, cbar_label) ax.set_xlabel( "Grid x", color=theme.COLOURS["text"]["axis"], fontproperties=theme.FONTS["axis"], ) ax.set_ylabel( "Grid y", color=theme.COLOURS["text"]["axis"], fontproperties=theme.FONTS["axis"], ) ax.set_facecolor("burlywood") viz_tools.set_aspect(ax) theme.set_axis_colors(ax)
def two_panel_plot(surfdat_1, surfdat_2, tit1, tit2, t_cmap, xsize, ysize, v_min1, v_max1, v_min2, v_max2, cl1, cl2, bigtit): "TESTED" from salishsea_tools import (teos_tools, tidetools, viz_tools) import matplotlib.pyplot as plt import cmocean as cm import numpy as np fig, axs = plt.subplots(1, 2, figsize=(xsize, ysize), sharey=True) cmap = t_cmap time_steps = (0, 1) for ax, t in zip(axs, time_steps): if t == 0: tplt = np.ma.masked_values(surfdat_1, 0) ax.set_title(tit1) v_min = v_min1 v_max = v_max1 clabel = cl1 if t == 1: tplt = np.ma.masked_values(surfdat_2, 0) ax.set_title(tit2) v_min = v_min2 v_max = v_max2 clabel = cl2 viz_tools.set_aspect(ax) mesh = ax.pcolormesh(tplt, cmap=t_cmap, vmin=v_min, vmax=v_max) cbar = fig.colorbar(mesh, ax=ax) cbar.set_label(clabel) ax.set_xlabel('x Index') axs[0].set_ylabel('y Index') cmap.set_bad('slategray') plt.suptitle(bigtit, fontsize=20)
def salinity_ferry_route( ferry_data_dir, grid_T_hr, bathy, route_name, dmy, figsize=(20, 7.5), ): """Plot daily salinity comparisons between ferry observations and model results as well as ferry route with model salinity distribution. :arg str ferry_data_dir: storage file location for ONC ferry data. :arg grid_T_hr: Hourly tracer results dataset from NEMO. :type grid_T_hr: :class:`netCDF4.Dataset :arg bathy: model bathymetry :type bathy: numpy array :arg str route_name: route name of these three ferry routes respectively :arg str dmy: date in form ddmonyy :arg 2-tuple figsize: Figure size (width, height) in inches. :returns: matplotlib figure object instance (fig). """ # Grid region to plot si, ei = 200, 610 sj, ej = 20, 370 lons = grid_T_hr.variables['nav_lon'][si:ei, sj:ej] lats = grid_T_hr.variables['nav_lat'][si:ei, sj:ej] # Salinity calculated by NEMO and observed by ONC ferry package model_depth_level = 1 # 1.5 m ## TODO: model time step for salinity contour map should be calculated from ## ferry route time model_time_step = 3 # 02:30 UTC sal_hr = grid_T_hr.variables['vosaline'] ## TODO: Use mesh mask instead of 0 for masking sal_masked = np.ma.masked_values( sal_hr[model_time_step, model_depth_level, si:ei, sj:ej], 0) sal_t = teos_tools.psu_teos(sal_masked) sal_obs = ferry_salinity(ferry_data_dir, route_name, dmy) nemo_a, nemo_b = nemo_sal_route(grid_T_hr, bathy, route_name, sal_obs) fig, axs = plt.subplots(1, 2, figsize=figsize) axs[1].set_axis_bgcolor("burlywood") viz_tools.set_aspect(axs[1], coords='map', lats=lats) cmap = plt.get_cmap('plasma') axs[1].set_xlim(-124.5, -122.5) axs[1].set_ylim(48.3, 49.6) # Plot model salinity mesh = axs[1].contourf(lons, lats, sal_t, 20, cmap=cmap) cbar = plt.colorbar(mesh, ax=axs[1]) cbar.ax.axes.tick_params(labelcolor='w') cbar.set_label('Absolute Salinity [g/kg]', color='white', **axis_font) axs[1].set_title('Ferry Route: 3am[UTC] 1.5m model result ', **title_font) axs[1].set_xlabel('Longitude [°E]', **axis_font) axs[1].set_ylabel('Latitude [°N]', **axis_font) # Plot ferry route. axs[1].plot(sal_obs[1], sal_obs[2], 'black', linewidth=4) figures.axis_colors(axs[1], 'grey') # Add locations and markers on plot for orientation bbox_args = dict(boxstyle='square', facecolor='white', alpha=0.7) places = [ FERRY_ROUTES[route_name]['start']['terminal'], FERRY_ROUTES[route_name]['end']['terminal'], 'Vancouver' ] label_offsets = [0.04, -0.4, 0.09] for stn, loc in zip(places, label_offsets): axs[1].plot(*PLACES[stn]['lon lat'], marker='D', color='white', markersize=10, markeredgewidth=2) axs[1].annotate( stn, (PLACES[stn]['lon lat'][0] + loc, PLACES[stn]['lon lat'][1]), fontsize=15, color='black', bbox=bbox_args) # Set up model part of salinity comparison plot axs[0].plot(sal_obs[1], nemo_a, 'DodgerBlue', linewidth=2, label=f'{FERRY_ROUTES[route_name]["start"]["hour"]} am [UTC]') axs[0].plot( sal_obs[1], nemo_b, 'MediumBlue', linewidth=2, label=f'{FERRY_ROUTES[route_name]["start"]["hour"]+1} am [UTC]') # Observational component of salinity comparisons plot axs[0].plot(sal_obs[1], sal_obs[3], 'DarkGreen', linewidth=2, label="Observed") axs[0].text(0.25, -0.1, 'Observations from Ocean Networks Canada', transform=axs[0].transAxes, color='white') axs[0].set_xlim(-124, -123) axs[0].set_ylim(10, 32) axs[0].set_title('Surface Salinity: ' + dmy, **title_font) axs[0].set_xlabel('Longitude', **axis_font) axs[0].set_ylabel('Absolute Salinity [g/kg]', **axis_font) axs[0].legend(loc=3) axs[0].grid(axis='both') fig.patch.set_facecolor('#2B3E50') figures.axis_colors(axs[0], 'grey') return fig
def _salinity_map_set_view(ax, lats): viz_tools.set_aspect(ax, coords="map", lats=lats) ax.set_xlim(-124.5, -122.5) ax.set_ylim(48.3, 49.6)
def clusters(ax1, year, var, no_clusters, markersize=20, legfontsize=12): colors = [ 'deepskyblue', 'red', 'goldenrod', 'forestgreen', 'midnightblue', 'orchid', 'gray', 'peru', 'olive', 'sandybrown', 'teal', 'pink', 'tan', 'yellow', 'thistle' ] import pickle import numpy as np import cmocean as cm import sys sys.path.append('./extraction_scripts') import map_fxn as mf from salishsea_tools import (viz_tools) bath = '/results/nowcast-sys/NEMO-forcing/grid/mesh_mask_SalishSea2.nc' grid = mf.import_bathy(bath) tpkl = f'./pkls/{var}_clustmat_{year}.pkl' cl = pickle.load(open(tpkl, 'rb')) cl_this = cl[no_clusters - 1, :] np.shape(cl_this) viz_tools.set_aspect(ax1) fmask = (grid.fmask[0, 0, :, :]) mesh = ax1.pcolormesh(fmask, vmin=0, vmax=1, cmap=cm.cm.deep) ax1.set_ylim([0, 898]) ax1.set_xlim([0, 398]) stn_x, stn_y = mf.make_stns(10) d_stn_x, d_stn_y = mf.filter_stn_in_domain(stn_x, stn_y, fmask) d_stn_xar = np.array(d_stn_x) d_stn_yar = np.array(d_stn_y) edge = np.where((d_stn_xar <= 10) | (d_stn_yar >= 888)) np.squeeze(edge) np.shape(edge) edgear = np.array(edge) edgear = edgear[0] d_stn_xar = np.delete(d_stn_xar, edge) d_stn_yar = np.delete(d_stn_yar, edge) #print(np.size(d_stn_xar)) ###sort clusters by size cluster_ids = np.arange(1, no_clusters + 1, 1) cluster_sizes = np.zeros_like(cluster_ids) #retrieve cluster sizes for j in range(1, no_clusters + 1): cluster = np.where(cl_this == j) cluster = np.squeeze(cluster) cluster_sizes[j - 1] = (np.size(cluster)) #sort cluster size matrix biggest to smallest cs = np.argsort(-cluster_sizes) #print(cs) #use those sizes to sort the cluster id list to corresponde to a list 'clust id, largest to smallest' new_cidlist = np.zeros_like(cluster_ids) for j in range(0, len(new_cidlist)): new_cidlist[j] = cluster_ids[cs[j]] #start plotting, plotting biggest cluster first, to keep colour order the same for j in range(0, np.size(new_cidlist)): cluster = np.where(cl_this == new_cidlist[j]) cluster = np.squeeze(cluster) c1_x = np.take(d_stn_xar, cluster) c1_y = np.take(d_stn_yar, cluster) pts = ax1.scatter(c1_x, c1_y, s=markersize, c=colors[j], label=str(new_cidlist[j]), marker='o') ax1.set_xticklabels(()) ax1.set_yticklabels(()) tit = var + ', year: ' + year + ' \n n. clusters = ' + str(no_clusters) ax1.legend(bbox_to_anchor=(1.1, 1), fontsize=legfontsize) ax1.set_title(tit, fontsize=legfontsize + 2)
def _make_figure_domain(coordf, bathyf, theme): """ Create surface currents tiled domain figure showing the boundary and labels of each tile. :param coordf: Path to Salish Sea NEMO model coordinates file. :type coordf: :py:class:`pathlib.Path` :param bathyf: Path to Salish Sea NEMO model bathymetry file. :type bathyf: :py:class:`pathlib.Path` :param theme: Module-like object that defines the style elements for the figure. See :py:mod:`nowcast.figures.website_theme` for an example. :returns: :py:class:`matplotlib.figure.Figure` and plot axes. """ if theme is None: fig = Figure(figsize=(8.5, 11), facecolor="white") else: fig = Figure(figsize=(5, 6), dpi=100, facecolor=theme.COLOURS["figure"]["facecolor"]) ax = fig.add_subplot(111) ax.grid(True) # Decorations title = "Salish Sea" x_label = "Longitude" y_label = "Latitude" if theme is None: ax.set_title(title, fontsize=10) ax.set_xlabel(x_label) ax.set_ylabel(y_label) else: ax.set_title( title, fontsize=10, color=theme.COLOURS["text"]["axis"], fontproperties=theme.FONTS["axis"], ) ax.set_xlabel( x_label, color=theme.COLOURS["text"]["axis"], fontproperties=theme.FONTS["axis"], ) ax.set_ylabel( y_label, color=theme.COLOURS["text"]["axis"], fontproperties=theme.FONTS["axis"], ) theme.set_axis_colors( ax) # Makes the x and y numbers and axis lines into near-white with netCDF4.Dataset(bathyf) as _dsBathy: viz_tools.plot_land_mask(ax, _dsBathy, coords="map", color="burlywood", zorder=-9) ax.set_rasterization_zorder(-1) viz_tools.plot_coastline(ax, _dsBathy, coords="map") with netCDF4.Dataset(coordf) as _dsCoord: coord_yt = _dsCoord.variables["gphit"][0, :, :] viz_tools.set_aspect(ax, coords="map", lats=coord_yt) _drawTile(tile_coords_dic, ax) return fig, ax
def test_set_aspect_map_explicit(self): axes = Mock() aspect = viz_tools.set_aspect(axes, 2 / 3, coords='map') axes.set_aspect.assert_called_once_with(2 / 3, adjustable='box') assert aspect == 2 / 3
def plume_maps(carp, grid, stns, ddmmmyy, rdir, humandate, dss_sig): tsal = grid.variables['vosaline'][0, 0, :, :] ttemp = grid.variables['votemper'][0, 0, :, :] tdic = carp.variables['dissolved_inorganic_carbon'][0, 0, :, :] tta = carp.variables['total_alkalinity'][0, 0, :, :] tsra = np.ravel(tsal) ttera = np.ravel(ttemp) ttara = np.ravel(tta) * 1e-3 tdra = np.ravel(tdic) * 1e-3 tzero = np.zeros_like(tsra) tpressure = np.zeros_like(tsra) tpressure[:] = 1 tzero = tpressure * 0 tsra_psu = tsra * 35 / 35.16504 response_tup = mocsy.mvars(temp=ttera, sal=tsra_psu, alk=ttara, dic=tdra, sil=tzero, phos=tzero, patm=tpressure, depth=tzero, lat=tzero, optcon='mol/m3', optt='Tpot', optp='m', optb='l10', optk1k2='m10', optkf='dg', optgas='Pinsitu') pH, pco2, fco2, co2, hco3, co3, OmegaA, OmegaC, BetaD, DENis, p, Tis = response_tup pHr = pH.reshape(898, 398) OmA = OmegaA.reshape(898, 398) surf_dat = [tsal, tdic, tta, ttemp, pHr, OmA] vmins = [15, 500, 500, 5, 7.5, 0] vmaxs = [30, 1800, 1800, 15, 8.5, 2] msk = [0, 0, 0, 0, 1e20, 1e20] cl = [ 'salinity psu', 'DIC umol/kg', 'TA umol/kg', 'temp deg C', 'pH', 'Omega A' ] t_cmap = [ cm.cm.haline, cm.cm.matter, cm.cm.matter, cm.cm.thermal, cm.cm.speed, cm.cm.curl ] fig, ((ax1, ax2, ax3), (ax4, ax5, ax6)) = \ plt.subplots(figsize=(17, 8.5) , nrows=2, ncols=3) viz_tools.set_aspect(ax1) viz_tools.set_aspect(ax2) viz_tools.set_aspect(ax3) viz_tools.set_aspect(ax4) viz_tools.set_aspect(ax5) viz_tools.set_aspect(ax6) y1 = 390 y2 = 460 x1 = 240 x2 = 398 i = 0 tplt0 = surf_dat[i][y1:y2, x1:x2] tplt = np.ma.masked_values(tplt0, msk[i]) tcmap = t_cmap[i] mesh = ax1.pcolormesh(tplt, cmap=tcmap, vmin=vmins[i], vmax=vmaxs[i]) cbar = fig.colorbar(mesh, ax=ax1) cbar.set_label(cl[i], fontsize=20) ax1.set_xticks([]) ax1.set_yticks([]) i = 1 tplt0 = surf_dat[i][y1:y2, x1:x2] tplt = np.ma.masked_values(tplt0, msk[i]) tcmap = t_cmap[i] mesh = ax2.pcolormesh(tplt, cmap=tcmap, vmin=vmins[i], vmax=vmaxs[i]) cbar = fig.colorbar(mesh, ax=ax2) cbar.set_label(cl[i], fontsize=20) ax2.set_xticks([]) ax2.set_yticks([]) i = 2 tplt0 = surf_dat[i][y1:y2, x1:x2] tplt = np.ma.masked_values(tplt0, msk[i]) tcmap = t_cmap[i] mesh = ax3.pcolormesh(tplt, cmap=tcmap, vmin=vmins[i], vmax=vmaxs[i]) cbar = fig.colorbar(mesh, ax=ax3) cbar.set_label(cl[i], fontsize=20) ax3.set_xticks([]) ax3.set_yticks([]) i = 3 tplt0 = surf_dat[i][y1:y2, x1:x2] tplt = np.ma.masked_values(tplt0, msk[i]) tcmap = t_cmap[i] mesh = ax4.pcolormesh(tplt, cmap=tcmap, vmin=vmins[i], vmax=vmaxs[i]) cbar = fig.colorbar(mesh, ax=ax4) cbar.set_label(cl[i], fontsize=20) ax4.set_xticks([]) ax4.set_yticks([]) i = 4 tplt0 = surf_dat[i][y1:y2, x1:x2] tplt = np.ma.masked_values(tplt0, msk[i]) tcmap = t_cmap[i] mesh = ax5.pcolormesh(tplt, cmap=tcmap, vmin=vmins[i], vmax=vmaxs[i]) cbar = fig.colorbar(mesh, ax=ax5) cbar.set_label(cl[i], fontsize=20) ax5.set_xticks([]) ax5.set_yticks([]) i = 5 tplt0 = surf_dat[i][y1:y2, x1:x2] tplt = np.ma.masked_values(tplt0, msk[i]) tcmap = t_cmap[i] mesh = ax6.pcolormesh(tplt, cmap=tcmap, vmin=vmins[i], vmax=vmaxs[i]) cbar = fig.colorbar(mesh, ax=ax6) cbar.set_label(cl[i], fontsize=20) ax6.set_xticks([]) ax6.set_yticks([]) cols = [] xs = [] ys = [] stn_in = [] for s in stns: col = stns[s]['color'] x = stns[s]['x'] y = stns[s]['y'] stn = stns[s]['code'] cols.append(col) xs.append(x) ys.append(y) stn_in.append(stn) #tcmap.set_bad('white') st = 'Fraser Plume Carbonate Chemistry, ' + humandate plt.suptitle(st, fontsize=20) fname = rdir + f'{ddmmmyy}_plume_' + dss_sig + '.png' fig.savefig(fname) #plt.show() plt.close()
def surface_buffer_maps(carp, grid, ddmmmyy, rdir, humandate, dss_sig): #retrieve relevant data for mocsy calculation, calculate mocsy tsal = grid.variables['vosaline'][0, 0, :, :] ttemp = grid.variables['votemper'][0, 0, :, :] tdic = carp.variables['dissolved_inorganic_carbon'][0, 0, :, :] tta = carp.variables['total_alkalinity'][0, 0, :, :] tsra = np.ravel(tsal) ttera = np.ravel(ttemp) ttara = np.ravel(tta) * 1e-3 tdra = np.ravel(tdic) * 1e-3 tzero = np.zeros_like(tsra) tpressure = np.zeros_like(tsra) tpressure[:] = 1 tzero = tpressure * 0 tsra_psu = tsra * 35 / 35.16504 ttera_is = gsw.t_from_CT(tsra, ttera, tzero) response_tup = mocsy.mvars(temp=ttera_is, sal=tsra_psu, alk=ttara, dic=tdra, sil=tzero, phos=tzero, patm=tpressure, depth=tzero, lat=tzero, optcon='mol/m3', optt='Tinsitu', optp='m', optb='l10', optk1k2='m10', optkf='dg', optgas='Pinsitu') pH, pco2, fco2, co2, hco3, co3, OmegaA, OmegaC, BetaD, DENis, p, Tis = response_tup #calculate borate and ohminus concentration bicarb = hco3 carb = co3 #calculate borate, Uppstrom, 1974, looked up in mocsy scl = tsra / 1.80655 borat = 0.000232 * scl / 10.811 hplus = 10**(-1 * pH) borat2 = .0000119 * tsra ohminus = ttara - bicarb - 2 * carb - borat # - calculates quantities needed for Egleston's factors, and the factors themselves #Khb is the acidity constant for boric acid - is this an appropriate ref? # https://www2.chemistry.msu.edu/courses/cem262/aciddissconst.html Khb = 5.81e-10 S = bicarb + 4 * (carb) + (hplus * borat) / (Khb + hplus) + hplus - ohminus P = 2 * (carb) + bicarb AlkC = bicarb + 2 * (carb) DIC = co2 + bicarb + carb #Alk = bicarb + 2*carb + borat - hplus + ohminus g_dic = DIC - AlkC**2 / S b_dic = (DIC * S - AlkC**2) / AlkC w_dic = DIC - (AlkC * P) / bicarb g_alk = (AlkC**2 - DIC * S) / AlkC b_alk = (AlkC**2 / DIC) - S w_alk = AlkC - (DIC * bicarb) / P #### g_dicR = g_dic.reshape(898, 398) * 1000 b_dicR = b_dic.reshape(898, 398) * 1000 w_dicR = w_dic.reshape(898, 398) * -1000 g_alkR = g_alk.reshape(898, 398) * -1000 b_alkR = b_alk.reshape(898, 398) * -1000 w_alkR = w_alk.reshape(898, 398) * 1000 surf_dat = [g_dicR, b_dicR, w_dicR, g_alkR, b_alkR, w_alkR] #ranges from nov 13,2014 hindcast. vmins = [-0.7, -0.4, -0.1, -0.4, -0.4, -0.1] vmaxs = [0.7, 1, 0.5, 1, 1, 0.4] msk = [1.875e+23, 5e+23, 6e+23, 5e+23, 5e+23, 2e+23] cl = ['$\gamma_{DIC}$', '$\\beta_{DIC}$', '-$\omega_{DIC}$',\ '$\gamma_{TA}$', '$\\beta_{TA}$', '-$\omega_{TA}$'] t_cmap = [cm.cm.oxy, cm.cm.oxy, cm.cm.oxy, cm.cm.oxy, cm.cm.oxy, cm.cm.oxy] fig, ((ax1, ax2, ax3), (ax4, ax5, ax6)) = \ plt.subplots(figsize=(20, 27) , nrows=2, ncols=3) viz_tools.set_aspect(ax1) viz_tools.set_aspect(ax2) viz_tools.set_aspect(ax3) viz_tools.set_aspect(ax4) viz_tools.set_aspect(ax5) viz_tools.set_aspect(ax6) i = 0 #'g_dicR', tplt0 = surf_dat[i] tplt = np.ma.masked_values(tplt0, 1.875e+23) tcmap = t_cmap[i] mesh = ax1.pcolormesh(tplt, cmap=tcmap, vmin=vmins[i], vmax=vmaxs[i]) cbar = fig.colorbar(mesh, ax=ax1) cbar.set_label(cl[i], fontsize=20) ax1.set_title('$CO_{2}$ with DIC', fontsize=22) i = 1 #'b_dicR', tplt0 = surf_dat[i] tplt = np.ma.masked_values(tplt0, 5e+23) tcmap = t_cmap[i] mesh = ax2.pcolormesh(tplt, cmap=tcmap, vmin=vmins[i], vmax=vmaxs[i]) cbar = fig.colorbar(mesh, ax=ax2) cbar.set_label(cl[i], fontsize=20) ax2.set_title('pH with DIC', fontsize=22) i = 2 #'-w_dicR', tplt0 = surf_dat[i] tplt = np.ma.masked_values(tplt0, 6e+23) tcmap = t_cmap[i] mesh = ax3.pcolormesh(tplt, cmap=tcmap, vmin=vmins[i], vmax=vmaxs[i]) cbar = fig.colorbar(mesh, ax=ax3) cbar.set_label(cl[i], fontsize=20) ax3.set_title('$\Omega$ with DIC', fontsize=22) i = 3 #'-g_alkR', tplt0 = surf_dat[i] tplt = np.ma.masked_values(tplt0, 5e+23) tcmap = t_cmap[i] mesh = ax4.pcolormesh(tplt, cmap=tcmap, vmin=vmins[i], vmax=vmaxs[i]) cbar = fig.colorbar(mesh, ax=ax4) cbar.set_label(cl[i], fontsize=20) ax4.set_title('$CO_{2}$ with TA', fontsize=22) i = 4 #'-b_alkR', tplt0 = surf_dat[i] tplt = np.ma.masked_values(tplt0, 5e+23) tcmap = t_cmap[i] mesh = ax5.pcolormesh(tplt, cmap=tcmap, vmin=vmins[i], vmax=vmaxs[i]) cbar = fig.colorbar(mesh, ax=ax5) cbar.set_label(cl[i], fontsize=20) ax5.set_title('pH with TA', fontsize=22) i = 5 #'w_alkR' tplt0 = surf_dat[i] tplt = np.ma.masked_values(tplt0, 2e+23) tcmap = t_cmap[i] mesh = ax6.pcolormesh(tplt, cmap=tcmap, vmin=vmins[i], vmax=vmaxs[i]) cbar = fig.colorbar(mesh, ax=ax6) cbar.set_label(cl[i], fontsize=20) ax6.set_title('$\Omega$ with TA', fontsize=22) #tcmap.set_bad('white') st = 'Carbonate Chemistry Buffer Factors, ' + humandate plt.suptitle(st, fontsize=20) fname = rdir + f'{ddmmmyy}_buffmap_' + dss_sig + '.png' fig.savefig(fname) plt.close()
def VENUS_location(grid_B, figsize=(10, 10)): """Plots the location of the VENUS Central, East and DDL nodes as well as Vancouver as a reference on a bathymetry map. :arg grid_B: Bathymetry dataset for the Salish Sea NEMO model. :type grid_B: :class:`netCDF4.Dataset` :arg figsize: Figure size (width, height) in inches. :type figsize: 2-tuple :returns: matplotlib figure object instance (fig). """ lats = grid_B.variables['nav_lat'][:] lons = grid_B.variables['nav_lon'][:] bathy = grid_B.variables['Bathymetry'][:] levels = np.arange(0, 470, 50) fig, ax = plt.subplots(1, 1, figsize=figsize) fig.patch.set_facecolor('#2B3E50') cmap = plt.get_cmap('winter_r') cmap.set_bad('burlywood') mesh = ax.contourf(lons, lats, bathy, levels, cmap=cmap, extend='both') cbar = fig.colorbar(mesh) viz_tools.plot_land_mask(ax, grid_B, coords='map', color='burlywood') viz_tools.plot_coastline(ax, grid_B, coords='map') viz_tools.set_aspect(ax) lon_c = SITES['VENUS']['Central']['lon'] lat_c = SITES['VENUS']['Central']['lat'] lon_e = SITES['VENUS']['East']['lon'] lat_e = SITES['VENUS']['East']['lat'] lon_d = SITES['VENUS']['ddl']['lon'] lat_d = SITES['VENUS']['ddl']['lat'] lon_v = SITES['Vancouver']['lon'] lat_v = SITES['Vancouver']['lat'] ax.plot( lon_c, lat_c, marker='D', color='Black', markersize=10, markeredgewidth=2) bbox_args = dict(boxstyle='square', facecolor='white', alpha=0.8) ax.annotate( 'Central', (lon_c - 0.11, lat_c + 0.04), fontsize=15, color='black', bbox=bbox_args) ax.plot( lon_e, lat_e, marker='D', color='Black', markersize=10, markeredgewidth=2) bbox_args = dict(boxstyle='square', facecolor='white', alpha=0.8) ax.annotate( 'East', (lon_e + 0.04, lat_e + 0.01), fontsize=15, color='black', bbox=bbox_args) ax.plot( lon_d, lat_d, marker='D', color='Black', markersize=10, markeredgewidth=2) bbox_args = dict(boxstyle='square', facecolor='white', alpha=0.8) ax.annotate( 'DDL', (lon_d + 0.01, lat_d + 0.05), fontsize=15, color='black', bbox=bbox_args) ax.plot( lon_v, lat_v, marker='D', color='DarkMagenta', markersize=10, markeredgewidth=2) bbox_args = dict(boxstyle='square', facecolor='white', alpha=0.8) ax.annotate( 'Vancouver', (lon_v - 0.15, lat_v + 0.04), fontsize=15, color='black', bbox=bbox_args) ax.set_xlim([-124.02, -123.02]) ax.set_ylim([48.5, 49.6]) plt.setp(plt.getp(cbar.ax.axes, 'yticklabels'), color='w') figures.axis_colors(ax, 'white') ax.set_xlabel('Longitude', **axis_font) ax.set_ylabel('Latitude', **axis_font) ax.set_title('VENUS Node Locations', **title_font) cbar.set_label('Depth [m]', **axis_font) return fig
def nice_CN_plot(tit1, tit2, plotdat, physdat, t, v_min, v_max, tcmap, clabel): "NOT TESTED" import netCDF4 as nc import matplotlib.pyplot as plt import datetime import os import numpy as np import cmocean as cm from salishsea_tools import visualisations as vis from salishsea_tools import (teos_tools, tidetools, viz_tools) import cmocean import glob fig, (axl, axr) = plt.subplots(1, 2, figsize=(16, 8)) land_colour = 'whitesmoke' zlevels = physdat.variables['deptht'] # Define the component slice to plot zmax, ylocn = 41, 424 section_slice = np.arange(208, 293) pdat = np.ma.masked_values(plotdat[t, :, 424, section_slice], 0) cmap = tcmap #cmap.set_bad(land_colour) #cmap.set_bad('whitesmoke') mesh = axl.pcolormesh( section_slice[:], zlevels[:zmax], pdat, cmap=cmap, vmin=v_min, vmax=v_max, ) axl.invert_yaxis() cbar = fig.colorbar(mesh, ax=axl) cbar.set_label(clabel) # Axes labels and title axl.set_xlabel('x Index') axl.set_ylabel('depth (m)') axl.set_title(tit1) # Axes limits and grid axl.set_xlim(section_slice[1], section_slice[-1]) axl.set_ylim(zlevels[zmax - 2] + 10, 0) axl.set_facecolor(land_colour) axl.grid() # Define surface current magnitude slice x_slice = np.arange(0, 398) y_slice = np.arange(0, 898) line_s = np.arange(0, 398) surf_dat = np.ma.masked_values(plotdat[t, 0, y_slice, x_slice], 0) viz_tools.set_aspect(axr) axr.plot( line_s, 424 * np.ones_like(line_s), linestyle='solid', linewidth=3, color='black', label='Section Line', ) cmap.set_bad(land_colour) #cmap.set_bad('whitesmoke') mesh = axr.pcolormesh(surf_dat, cmap=tcmap, vmin=v_min, vmax=v_max) # Axes labels and title axr.set_xlabel('') axr.set_ylabel('') axr.set_xticks([]) axr.set_yticks([]) axr.set_title(tit2) legend = axr.legend(loc='best', fancybox=True, framealpha=0.25) axr.grid()
def update_frame(t, t_array=t_array, t_y_min=t_y_min, t_y_max=t_y_max, t_x_min=t_x_min, t_x_max=t_x_max, t_maxval=t_maxval, c_array=c_array, c_y_min=c_y_min, c_y_max=c_y_max, c_x_min=c_x_min, c_x_max=c_x_max, c_maxval=c_maxval, times=time_values, t_mask=t_mask, c_mask=c_mask, t_q_mask=t_q_mask, c_q_mask=c_q_mask, current=currents, wind=winds, currents_start=currents_start, winds_start=winds_start): # set up the subplot layout grid = plt.GridSpec(2, 3) # !---------------------------------------------------------------------------------------------------------------------------- # plot the surface oil thickness ax = plt.subplot(grid[0:, 0]) thickness = t_array[t] # get whatever should be in the scope scope_result = make_scope(thickness) if scope_result is (False or None): scope = False else: scope, ys_min, ys_max, xs_min, xs_max = scope_result # for the horizontal markers on the colorbar thickmin, thickmax = thickness.min(), thickness.max() # mask out the zeros condlist = [thickness == 0, thickness != 0] choicelist = [np.nan, thickness] thickness = np.select(condlist, choicelist) # plot full region normalised to log scale plt.pcolormesh(thickness, animated=True, norm=colors.LogNorm(vmin=0.0001, vmax=t_maxval), vmin=0.0001, vmax=t_maxval, cmap='inferno') # plot the scope boundaries if scope is not False: plt.hlines(ys_max, xmin=xs_min, xmax=xs_max, colors='Green') plt.hlines(ys_min, xmin=xs_min, xmax=xs_max, colors='Green') plt.vlines(xs_max, ymin=ys_min, ymax=ys_max, colors='Green') plt.vlines(xs_min, ymin=ys_min, ymax=ys_max, colors='Green') # plot colorbar normalised to log scale, with current min and max thicknesses cbar = plt.colorbar( plt.pcolormesh(np.meshgrid(np.array([0.0001, t_maxval])), norm=colors.LogNorm(vmin=0.0001, vmax=t_maxval), cmap='inferno')) cbar.ax.get_yaxis().labelpad = 10 cbar.ax.set_ylabel('Oil thickness (microns)', rotation=270) cbar.ax.hlines(thickmax, xmin=0, xmax=1000, colors='Red') cbar.ax.hlines(thickmin, xmin=0, xmax=1000, colors='Blue') # plot the land mask and coastline plt.contourf(t_mask, levels=[-0.1, 0.1], colors='Burlywood') plt.contour(t_mask, levels=[-0.1, 0.1], colors='k') # thickness limits readouts plt.title(f'max thickness {thickmax}\nmin thickness {thickmin}') # plot current quivers U, V = current_quivers(current, t + currents_start, t_y_min, t_y_max, t_x_min, t_x_max) # mask out everything but every nth quiver U_ma, V_ma = ma.array(U, mask=t_q_mask), ma.array(V, mask=t_q_mask) currentq = plt.quiver(U_ma, V_ma, scale=20, width=0.003) plt.quiverkey(currentq, 0, 1.08, 2, label='Current (2 m/s)', transform=ax.transAxes) u, v = wind_quivers(wind, t + winds_start, t_y_min, t_y_max, t_x_min, t_x_max) u, v = np.average(u), np.average(v) windq = plt.quiver(10, t_y_max - t_y_min - 10, u, v, scale=20, color='Red') plt.quiverkey(windq, 1, 1.08, 5, label='Wind (5 m/s)', transform=ax.transAxes) viz_tools.set_aspect(ax) # !----------------------------------------------------------------------------------------------------------------------------- # plot the 2D thickness scope ax = plt.subplot(grid[0, 2]) if scope is False: plt.cla() plt.xticks([]) plt.yticks([]) else: # mask out the scope contants, plot land mask and coastline condlist = [scope == 0, scope != 0] choicelist = [np.nan, scope] plt.pcolormesh(np.select(condlist, choicelist), animated=True, norm=colors.LogNorm(vmin=0.0001, vmax=t_maxval), vmin=0.0001, vmax=t_maxval, cmap='inferno') scope_mask = t_mask[ys_min:ys_max, xs_min:xs_max] plt.contourf(scope_mask, levels=[-0.1, 0.1], colors='Burlywood') plt.contour(scope_mask, levels=[-0.1, 0.1], colors='k') # plot the quivers U, V = U_ma[ys_min:ys_max, xs_min:xs_max], V_ma[ys_min:ys_max, xs_min:xs_max] plt.quiver(U, V, scale=20, width=0.003, headwidth=3) # remove axis ticks plt.xticks([]) plt.yticks([]) plt.title('Oil Thickness Scope') # !---------------------------------------------------------------------------------------------------------------------------- ax = plt.subplot(grid[0:, 1]) concentration = c_array[t] # get whatever should be in the scope scope_result = make_scope(concentration) if scope_result is (False or None): scope = False else: scope, ys_min, ys_max, xs_min, xs_max = scope_result # for the horizontal markers on the colorbar concmin, concmax = concentration.min(), concentration.max() # mask out the zeros condlist = [concentration == 0, concentration != 0] choicelist = [np.nan, concentration] concentration = np.select(condlist, choicelist) # plot full region normalised to log scale plt.pcolormesh(concentration, animated=True, norm=colors.LogNorm(vmin=0.0001, vmax=c_maxval), vmin=0.0001, vmax=c_maxval, cmap='inferno') # plot the scope boundaries if scope is not False: plt.hlines(ys_max, xmin=xs_min, xmax=xs_max, colors='Green') plt.hlines(ys_min, xmin=xs_min, xmax=xs_max, colors='Green') plt.vlines(xs_max, ymin=ys_min, ymax=ys_max, colors='Green') plt.vlines(xs_min, ymin=ys_min, ymax=ys_max, colors='Green') # plot colorbar normalised to log scale, with current min and max concentrations cbar = plt.colorbar( plt.pcolormesh(np.meshgrid(np.array([0.0001, c_maxval])), norm=colors.LogNorm(vmin=0.0001, vmax=c_maxval), cmap='inferno')) cbar.ax.get_yaxis().labelpad = 10 cbar.ax.set_ylabel('Oil concentration (ppm)', rotation=270) cbar.ax.hlines(concmax, xmin=0, xmax=1000, colors='Red') cbar.ax.hlines(concmin, xmin=0, xmax=1000, colors='Blue') # plot the land mask and coastline plt.contourf(c_mask, levels=[-0.1, 0.1], colors='Burlywood') plt.contour(c_mask, levels=[-0.1, 0.1], colors='k') # thickness limits readouts plt.title(f'max concentration {concmax}\nmin concentration {concmin}') # plot current quivers U, V = current_quivers(current, t + currents_start, c_y_min, c_y_max, c_x_min, c_x_max) # mask out everything but every nth quiver U_ma, V_ma = ma.array(U, mask=c_q_mask), ma.array(V, mask=c_q_mask) currentq = plt.quiver(U_ma, V_ma, scale=20, width=0.003) plt.quiverkey(currentq, 0.0, 1.08, 2, label='Current (2 m/s)', transform=ax.transAxes) u, v = wind_quivers(wind, t + winds_start, c_y_min, c_y_max, c_x_min, c_x_max) u, v = np.average(u), np.average(v) windq = plt.quiver(10, c_y_max - c_y_min - 10, u, v, scale=20, color='Red') plt.quiverkey(windq, 1.0, 1.08, 5, label='Wind (5 m/s)', transform=ax.transAxes) viz_tools.set_aspect(ax) # !------------------------------------------------------------------------------------------------------------------------------ ax = plt.subplot(grid[1, 2]) if scope is False: plt.cla() plt.xticks([]) plt.yticks([]) else: # mask out the scope contants, plot land mask and coastline condlist = [scope == 0, scope != 0] choicelist = [np.nan, scope] plt.pcolormesh(np.select(condlist, choicelist), animated=True, norm=colors.LogNorm(vmin=0.0001, vmax=c_maxval), vmin=0.0001, vmax=c_maxval, cmap='inferno') scope_mask = c_mask[ys_min:ys_max, xs_min:xs_max] plt.contourf(scope_mask, levels=[-0.1, 0.1], colors='Burlywood') plt.contour(scope_mask, levels=[-0.1, 0.1], colors='k') # plot the quivers U, V = U_ma[ys_min:ys_max, xs_min:xs_max], V_ma[ys_min:ys_max, xs_min:xs_max] plt.quiver(U, V, scale=20, width=0.003, headwidth=3) # remove axis ticks plt.xticks([]) plt.yticks([]) plt.title('Oil Concentration Scope') #plt.tight_layout() plt.suptitle(times[t], y=0.99)
def update_frame(t, t_array=t_array, t_y_min=t_y_min, t_y_max=t_y_max, t_x_min=t_x_min, t_x_max=t_x_max, t_maxval=t_maxval, times=time_values, t_mask=t_mask, t_q_mask=t_q_mask, avg_norm=avg_norm, min_norm=min_norm, max_norm=max_norm, avg_abnorm=avg_abnorm, min_abnorm=min_abnorm, max_abnorm=max_abnorm, max_ylim=max_ylim, min_ylim=min_ylim, smax_ylim=smax_ylim, smin_ylim=smin_ylim, currents_start=currents_start, winds_start=winds_start, current=currents, wind=winds, tim_norm=time_norm, time_abnorm=time_abnorm): # !---------------------------------------------------------------------------------------------------------------------------- grid = plt.GridSpec(2, 3) ax = plt.subplot(grid[0:, 0]) # plot the surface oil thickness thickness = t_array[t] # for the horizontal markers on the colorbar thickmin, thickmax = thickness.min(), thickness.max() # mask out the zeros condlist = [thickness == 0, thickness != 0] choicelist = [np.nan, thickness] thickness = np.select(condlist, choicelist) # plot full region normalised to log scale plt.pcolormesh(thickness, animated=True, norm=colors.LogNorm(vmin=0.0001, vmax=t_maxval), vmin=0.0001, vmax=t_maxval, cmap='inferno') # plot colorbar normalised to log scale, with current min and max thicknesses cbar = plt.colorbar( plt.pcolormesh(np.meshgrid(np.array([0.0001, t_maxval])), norm=colors.LogNorm(vmin=0.0001, vmax=t_maxval), cmap='inferno')) cbar.ax.get_yaxis().labelpad = 25 cbar.ax.set_ylabel('Oil thickness (microns)', rotation=270) cbar.ax.hlines(thickmax, xmin=0, xmax=150, colors='Red') cbar.ax.hlines(thickmin, xmin=0, xmax=150, colors='Blue') # plot the land mask and coastline plt.contourf(t_mask, levels=[-0.1, 0.1], colors='Burlywood') plt.contour(t_mask, levels=[-0.1, 0.1], colors='k') # thickness limits readouts plt.title(f'max thickness {thickmax}\nmin thickness {thickmin}') # plot current quivers U, V = current_quivers(current, t + currents_start, t_y_min, t_y_max, t_x_min, t_x_max) # mask out everything but every nth quiver U_ma, V_ma = ma.array(U, mask=t_q_mask), ma.array(V, mask=t_q_mask) currentq = plt.quiver(U_ma, V_ma, scale=20, width=0.003) plt.quiverkey(currentq, 1.13, 1.92, 1, label='Current (1 m/s)', transform=ax.transAxes) u, v = wind_quivers(wind, t + winds_start, t_y_min, t_y_max, t_x_min, t_x_max) u, v = np.average(u), np.average(v) windq = plt.quiver(10, t_y_max - t_y_min - 10, u, v, scale=20, color='Red') plt.quiverkey(windq, 1.13, 1.8, 5, label='Wind (5 m/s)', transform=ax.transAxes) viz_tools.set_aspect(ax) # !----------------------------------------------------------------------------------------------------------------------------- # plot the ssh ax = plt.subplot(grid[0, 1:]) plt.plot(time_norm, avg_norm, 'b-', label='average sossheig w/ oil') plt.plot(time_norm, min_norm, 'b:', label='max sossheig w/ oil') plt.plot(time_norm, max_norm, 'b--', label='min sossheig w/ oil') plt.plot(time_abnorm, avg_abnorm, 'r-', label='average sossheig w/o oil') plt.plot(time_abnorm, min_abnorm, 'r:', label='max sossheig w/o oil') plt.plot(time_abnorm, max_abnorm, 'r--', label='min sossheig w/o oil') ax.set_xlim(xmin=times[0], xmax=times[-1]) ax.axvline(x=times[t], ymin=min_ylim, ymax=max_ylim) plt.legend() plt.title('Sea surface height (m)') # !---------------------------------------------------------------------------------------------------------------------------- ax = plt.subplot(grid[1, 1:]) plt.plot(time_norm, savg_norm, 'b-', label='average whitecap coverage w/ oil') plt.plot(time_norm, smin_norm, 'b:', label='max whitecap coverage w/ oil') plt.plot(time_norm, smax_norm, 'b--', label='min whitecap coverage w/ oil') plt.plot(time_abnorm, savg_abnorm, 'r-', label='average whitecap coverage w/o oil') plt.plot(time_abnorm, smin_abnorm, 'r:', label='max whitecap coverage w/o oil') plt.plot(time_abnorm, smax_abnorm, 'r--', label='min whitecap coverage w/o oil') ax.set_xlim(xmin=times[0], xmax=times[-1]) ax.axvline(x=times[t], ymin=smin_ylim, ymax=smax_ylim) plt.legend() plt.title('Whitecap Coverage (m)') #plt.tight_layout() print(t)
def VENUS_location(grid_B, figsize=(10, 10)): """Plots the location of the VENUS Central, East and DDL nodes as well as Vancouver as a reference on a bathymetry map. :arg grid_B: Bathymetry dataset for the Salish Sea NEMO model. :type grid_B: :class:`netCDF4.Dataset` :arg figsize: Figure size (width, height) in inches. :type figsize: 2-tuple :returns: matplotlib figure object instance (fig). """ lats = grid_B.variables["nav_lat"][:] lons = grid_B.variables["nav_lon"][:] bathy = grid_B.variables["Bathymetry"][:] levels = np.arange(0, 470, 50) fig, ax = plt.subplots(1, 1, figsize=figsize) fig.patch.set_facecolor("#2B3E50") cmap = plt.get_cmap("winter_r") cmap.set_bad("burlywood") mesh = ax.contourf(lons, lats, bathy, levels, cmap=cmap, extend="both") cbar = fig.colorbar(mesh) viz_tools.plot_land_mask(ax, grid_B, coords="map", color="burlywood") viz_tools.plot_coastline(ax, grid_B, coords="map") viz_tools.set_aspect(ax) lon_c = SITES["VENUS"]["Central"]["lon"] lat_c = SITES["VENUS"]["Central"]["lat"] lon_e = SITES["VENUS"]["East"]["lon"] lat_e = SITES["VENUS"]["East"]["lat"] lon_d = SITES["VENUS"]["ddl"]["lon"] lat_d = SITES["VENUS"]["ddl"]["lat"] lon_v = SITES["Vancouver"]["lon"] lat_v = SITES["Vancouver"]["lat"] ax.plot(lon_c, lat_c, marker="D", color="Black", markersize=10, markeredgewidth=2) bbox_args = dict(boxstyle="square", facecolor="white", alpha=0.8) ax.annotate( "Central", (lon_c - 0.11, lat_c + 0.04), fontsize=15, color="black", bbox=bbox_args, ) ax.plot(lon_e, lat_e, marker="D", color="Black", markersize=10, markeredgewidth=2) bbox_args = dict(boxstyle="square", facecolor="white", alpha=0.8) ax.annotate("East", (lon_e + 0.04, lat_e + 0.01), fontsize=15, color="black", bbox=bbox_args) ax.plot(lon_d, lat_d, marker="D", color="Black", markersize=10, markeredgewidth=2) bbox_args = dict(boxstyle="square", facecolor="white", alpha=0.8) ax.annotate("DDL", (lon_d + 0.01, lat_d + 0.05), fontsize=15, color="black", bbox=bbox_args) ax.plot(lon_v, lat_v, marker="D", color="DarkMagenta", markersize=10, markeredgewidth=2) bbox_args = dict(boxstyle="square", facecolor="white", alpha=0.8) ax.annotate( "Vancouver", (lon_v - 0.15, lat_v + 0.04), fontsize=15, color="black", bbox=bbox_args, ) ax.set_xlim([-124.02, -123.02]) ax.set_ylim([48.5, 49.6]) plt.setp(plt.getp(cbar.ax.axes, "yticklabels"), color="w") axis_colors(ax, "white") ax.set_xlabel("Longitude", **axis_font) ax.set_ylabel("Latitude", **axis_font) ax.set_title("VENUS Node Locations", **title_font) cbar.set_label("Depth [m]", **axis_font) return fig
def _makeTiles( t_index, dsU, dsV, dsCoord, dsMask, dsBathy, theme, tile_coords_dic, expansion_factor, ): """ Produce surface current tile figures for each tile at time index t_index """ units = dsU.variables["time_counter"].units calendar = dsU.variables["time_counter"].calendar maskU, maskV = _prepareVelocity(t_index, dsU, dsV, dsCoord, dsMask) coord_xt, coord_yt = _prepareCoordinates(dsCoord) k = 3 tiles = [] figs = [] for tile, values in tile_coords_dic.items(): x1, x2, y1, y2 = values[0], values[1], values[2], values[3] sec = dsU.variables["time_counter"][t_index] if theme is None: fig = Figure(figsize=(8.5, 11), facecolor="white") else: fig = Figure( figsize=(11, 9), facecolor=theme.COLOURS["figure"]["facecolor"] ) ax = fig.add_subplot(111) X, Y = coord_xt[::k, ::k].flatten(), coord_yt[::k, ::k].flatten() U, V = maskU[::k, ::k].flatten(), maskV[::k, ::k].flatten() i = numpy.logical_not(U.mask) XC, YC, UC, VC = X[i], Y[i], U[i].data, V[i].data # Add some vectors in the middle of the Atlantic to ensure we get at least one for each arrow size tempU = numpy.linspace(0, 5, 50) zeros = numpy.zeros(tempU.shape) XC = numpy.concatenate([XC, zeros]) YC = numpy.concatenate([YC, zeros]) UC = numpy.concatenate([UC, tempU]) VC = numpy.concatenate([VC, zeros]) SC = numpy.sqrt(UC ** 2 + VC ** 2) i = SC < 0.05 if numpy.any(i): UCC, VCC, XCC, YCC = _cut(UC, VC, XC, YC, i) ax.scatter(XCC, YCC, s=2, c="k") # Arrow parameters: list of tuples of (speed_min, speed_max, arrow_width, arrow_head_width) arrowparamslist = [ (0.05, 0.25, 0.003, 3.00), (0.25, 0.50, 0.005, 2.75), (0.50, 1.00, 0.007, 2.25), (1.00, 1.50, 0.009, 2.00), (1.50, 2.00, 0.011, 1.50), (2.00, 2.50, 0.013, 1.25), (2.50, 3.00, 0.015, 1.00), (3.00, 4.00, 0.017, 0.75), (4.00, 100, 0.020, 2.00), ] if theme is None: # Quiver key positions (x,y) relative to axes that spans [0,1]x[0,1] positionslist = [ (0.55, 1.14), (0.55, 1.10), (0.55, 1.06), (0.55, 1.02), (0.80, 1.18), (0.80, 1.14), (0.80, 1.10), (0.80, 1.06), (0.80, 1.02), ] FP = None ax.text(0.53, 1.17, r"$\bullet$ < 0.05 m/s", transform=ax.transAxes) else: # Quiver key positions (x,y) relative to axes that spans [0,1]x[0,1] positionslist = [ (1.05, 0.95), (1.05, 0.90), (1.05, 0.85), (1.05, 0.80), (1.05, 0.75), (1.05, 0.70), (1.05, 0.65), (1.05, 0.60), (1.05, 0.55), ] FP = theme.FONTS["axis"] fontsize = FP.get_size() - 4 ax.text( 1.03, 0.98, r"$\bullet$ < 0.05 m/s", color=theme.COLOURS["text"]["axis"], fontsize=fontsize, transform=ax.transAxes, ) # Draw each arrow for arrowparams, positions in zip(arrowparamslist, positionslist): _drawArrows(arrowparams, positions, UC, VC, XC, YC, SC, ax, theme, FP) ax.grid(True) # Use expansion factor to set axes limits dx = (x2 - x1) * expansion_factor dy = (y2 - y1) * expansion_factor ax.set_xlim([x1 - dx, x2 + dx]) ax.set_ylim([y1 - dy, y2 + dy]) # Decorations title = _createTileTitle(sec, units, calendar) + "\n" + tile x_label = "Longitude" y_label = "Latitude" if theme is None: title_notheme = "SalishSeaCast Surface Currents\n" + title + "\n" ax.set_title(title_notheme, fontsize=12, loc="left") ax.set_xlabel(x_label) ax.set_ylabel(y_label) else: ax.set_title( title, fontsize=10, color=theme.COLOURS["text"]["axis"], fontproperties=FP, ) ax.set_xlabel( x_label, fontsize=8, color=theme.COLOURS["text"]["axis"], fontproperties=FP, ) ax.set_ylabel( y_label, color=theme.COLOURS["text"]["axis"], fontproperties=FP ) theme.set_axis_colors( ax ) # Makes the x and y numbers and axis lines into near-white x_tick_loc = ax.get_xticks() x_tick_label = ["{:.1f}".format(q) for q in x_tick_loc] ax.set_xticklabels(x_tick_label, rotation=45) viz_tools.plot_land_mask( ax, dsBathy, coords="map", color="burlywood", zorder=-9 ) ax.set_rasterization_zorder(-1) viz_tools.plot_coastline(ax, dsBathy, coords="map") viz_tools.set_aspect(ax, coords="map", lats=coord_yt) tiles += [tile] figs += [fig] return figs, tiles
def ONC_animator(plotdat, tstart, tend, v_min, v_max, stepsize, tit1, tit2, figtit, dirstr, tcmap, clabel, indexer): import numpy as np import netCDF4 as nc import cmocean as cm import matplotlib.pyplot as plt from salishsea_tools import (teos_tools, tidetools, viz_tools) for i in range(tstart, tend): fig, (axl, axr) = plt.subplots(1, 2, figsize=(16, 8)) land_colour = 'whitesmoke' daypath = '/results/SalishSea/nowcast-blue/01dec17/SalishSea_1d_20171201_20171201_grid_T.nc' t_d = nc.Dataset(daypath) zlevels = t_d.variables['deptht'] # Define the component slice to plot zmax, ylocn = 41, 424 section_slice = np.arange(208, 293) pdat = np.ma.masked_values(plotdat[i, :, 424, section_slice], 0) cmap = tcmap mesh = axl.pcolormesh( section_slice[:], zlevels[:zmax], pdat, cmap=cmap, vmin=v_min, vmax=v_max, ) axl.invert_yaxis() cbar = fig.colorbar(mesh, ax=axl) cbar.set_label(clabel) # Axes labels and title axl.set_xlabel('x Index') axl.set_ylabel('depth (m)') axl.set_title(tit1) # Axes limits and grid axl.set_xlim(section_slice[1], section_slice[-1]) axl.set_ylim(zlevels[zmax - 2] + 10, 0) axl.set_facecolor(land_colour) axl.grid() # Define surface current magnitude slice x_slice = np.arange(0, 398) y_slice = np.arange(0, 898) line_s = np.arange(0, 398) surf_dat = np.ma.masked_values(plotdat[i, 0, y_slice, x_slice], 0) viz_tools.set_aspect(axr) axr.plot( line_s, 424 * np.ones_like(line_s), linestyle='solid', linewidth=3, color='black', label='Section Line', ) cmap.set_bad(land_colour) mesh = axr.pcolormesh(surf_dat, cmap=tcmap, vmin=v_min, vmax=v_max) # Axes labels and title axr.set_xlabel('') axr.set_ylabel('') axr.set_xticks([]) axr.set_yticks([]) axr.set_title(tit2) legend = axr.legend(loc='best', fancybox=True, framealpha=0.25) axr.grid() t_i = indexer + i si = str(t_i) #print(len(si)) if len(si) == 1: lsi = '00' + si if len(si) == 2: lsi = '0' + si if len(si) == 3: lsi = si print(lsi) fig.suptitle(figtit + str(i)) fig.savefig(dirstr + figtit + str(lsi)) plt.close(fig)
def pHOmpco2_thres(carp, grid, ddmmmyy, rdir, humandate, dss_sig, pH_M, pCO2_M, OmA_M, pH_T, pCO2_T, OmA_T): tsal = grid.variables['vosaline'][0, 0, :, :] ttemp = grid.variables['votemper'][0, 0, :, :] tdic = carp.variables['dissolved_inorganic_carbon'][0, 0, :, :] tta = carp.variables['total_alkalinity'][0, 0, :, :] tsra = np.ravel(tsal) ttera = np.ravel(ttemp) ttara = np.ravel(tta) * 1e-3 tdra = np.ravel(tdic) * 1e-3 tzero = np.zeros_like(tsra) tpressure = np.zeros_like(tsra) tpressure[:] = 1 tzero = tpressure * 0 tsra_psu = tsra * 35 / 35.16504 response_tup = mocsy.mvars(temp=ttera, sal=tsra_psu, alk=ttara, dic=tdra, sil=tzero, phos=tzero, patm=tpressure, depth=tzero, lat=tzero, optcon='mol/m3', optt='Tpot', optp='m', optb='l10', optk1k2='m10', optkf='dg', optgas='Pinsitu') pH, pco2, fco2, co2, hco3, co3, OmegaA, OmegaC, BetaD, DENis, p, Tis = response_tup pHr = pH.reshape(898, 398) OmA = OmegaA.reshape(898, 398) pco2R = pco2.reshape(898, 398) #surf_dat = [tsal, tdic, tta, ttemp, pHr, OmA] surf_dat = [pHr, OmA, pco2R] print(OmA[20, 250]) print(pHr[20, 250]) print(pco2R[20, 250]) pH_20 = pH_T - pH_M pH_MX = pH_M + (pH_20 * 5) OmA_20 = OmA_T - OmA_M OmA_MX = OmA_M + (OmA_20 * 5) pCO2_20 = pCO2_T - pCO2_M pCO2_MX = pCO2_M + (pCO2_20 * 5) vmins = [pH_M, OmA_M, pCO2_M] vmaxs = [pH_MX, OmA_MX, pCO2_MX] msk = [1e20, 1e20, 1e20] cl = ['pH', 'Omega A', 'pCO2'] t_cmap = [cm.cm.oxy, cm.cm.oxy, cm.cm.oxy] fig, ((ax1, ax2, ax3)) = \ plt.subplots(figsize=(17, 8.5) , nrows=1, ncols=3) viz_tools.set_aspect(ax1) viz_tools.set_aspect(ax2) viz_tools.set_aspect(ax3) y1 = 0 y2 = 898 x1 = 0 x2 = 398 i = 0 tplt0 = surf_dat[i][y1:y2, x1:x2] tplt = np.ma.masked_values(tplt0, msk[i]) tcmap = t_cmap[i] mesh = ax1.pcolormesh(tplt, cmap=tcmap, vmin=vmins[i], vmax=vmaxs[i]) cbar = fig.colorbar(mesh, ax=ax1) cbar.set_label(cl[i], fontsize=20) ax1.set_xticks([]) ax1.set_yticks([]) i = 1 tplt0 = surf_dat[i][y1:y2, x1:x2] tplt = np.ma.masked_values(tplt0, msk[i]) tcmap = t_cmap[i] mesh = ax2.pcolormesh(tplt, cmap=tcmap, vmin=vmins[i], vmax=vmaxs[i]) cbar = fig.colorbar(mesh, ax=ax2) cbar.set_label(cl[i], fontsize=20) ax2.set_xticks([]) ax2.set_yticks([]) i = 2 tplt0 = surf_dat[i][y1:y2, x1:x2] tplt = np.ma.masked_values(tplt0, msk[i]) tcmap = t_cmap[i] mesh = ax3.pcolormesh(tplt, cmap=tcmap, vmin=vmins[i], vmax=vmaxs[i]) cbar = fig.colorbar(mesh, ax=ax3) cbar.set_label(cl[i], fontsize=20) ax3.set_xticks([]) ax3.set_yticks([]) st = 'pH, pCO2, Omega_A threshold plots, ' + humandate plt.suptitle(st, fontsize=20) fname = rdir + f'{ddmmmyy}_pHT_' + dss_sig + '.png' fig.savefig(fname) plt.show()
def test_set_aspect_defaults(self): axes = Mock() aspect = viz_tools.set_aspect(axes) axes.set_aspect.assert_called_once_with(5 / 4.4, adjustable='box') assert aspect == 5 / 4.4
def DispGridLocs(mesh_mask='/ocean/eolson/MEOPAR/NEMO-forcing/grid/mesh_mask201702_noLPE.nc'): """Display locations in NEMO model grid coordinates :arg mesh_mask: string with path to the meshmask you would like to plot; 201702 default :type mesh_mask: str :returns: figure handle :rtype: :py:class:`matplotlib.figure.Figure` """ import numpy as np # only grid from mpl_toolkits.basemap import Basemap import netCDF4 as nc # only grid from matplotlib import pyplot as plt from salishsea_tools import viz_tools # only grid places2=PLACES.copy() with nc.Dataset(mesh_mask) as fm: tmask=np.copy(fm.variables['tmask']) e3t_0=np.copy(fm.variables['e3t_0']) bathy=np.sum(e3t_0[0,:,:,:]*tmask[0,:,:,:],0) cm=plt.cm.get_cmap('Blues') cm.set_bad('lightgray') fig,ax=plt.subplots(1,2,figsize=(18,18)) viz_tools.set_aspect(ax[0]) viz_tools.set_aspect(ax[1]) ax[0].pcolormesh(np.ma.masked_where(tmask[0,0,:,:]==0,bathy),cmap=plt.cm.get_cmap('Blues')) # map stations: for pl in places2.keys(): if 'NEMO grid ji' in places2[pl].keys() and places2[pl]['NEMO grid ji'] is not None: j,i=places2[pl]['NEMO grid ji'] if pl in ('Sandy Cove','Calamity Point','Port Moody','Vancouver','New Westminster', 'East Node','Duke Pt.','Halibut Bank','Cherry Point','Central SJDF','Friday Harbor'): ax[0].plot(i,j,'ro') ax[0].text(i+4,j,pl,fontsize=10,fontweight='bold', ha='left',va='center',color='r') elif pl in ('Sand Heads','Delta DDL node','Central Node','Delta BBL node','Cluster_9', 'East Node','Woodwards Landing'): ax[0].plot(i,j,'ro') else: ax[0].plot(i,j,'ro') ax[0].text(i-4,j,pl,fontsize=10,fontweight='bold', ha='right',va='center',color='r') xl=(240,340) yl=(400,450) ax[1].pcolormesh(np.ma.masked_where(tmask[0,0,:,:]==0,bathy),cmap=plt.cm.get_cmap('Blues')) # map stations: for pl in places2.keys(): if 'NEMO grid ji' in places2[pl].keys() and places2[pl]['NEMO grid ji'] is not None: j,i=places2[pl]['NEMO grid ji'] if (xl[0]<i<xl[1]) & (yl[0]<j<yl[1]): if pl in ('Sandy Cove','Calamity Point','Port Moody','Vancouver','New Westminster','Friday Harbor', 'East Node','Duke Point','Halibut Bank','Cherry Point', 'Sand Heads','Cluster_9','Central SJDF'): ax[1].plot(i,j,'ro') ax[1].text(i+1,j,pl,fontsize=10,fontweight='bold', ha='left',va='center',color='r') elif pl in ('Delta BBL node'): ax[1].plot(i,j,'ro') ax[1].text(i,j-2,pl,fontsize=10,fontweight='bold', ha='center',va='center',color='r') elif pl in ('Delta DDL node'): ax[1].plot(i,j,'ro') ax[1].text(i,j+2,pl,fontsize=10,fontweight='bold', ha='right',va='center',color='r') else: ax[1].plot(i,j,'ro') ax[1].text(i-1,j,pl,fontsize=10,fontweight='bold', ha='right',va='center',color='r') ax[1].set_xlim(xl[0],xl[1]) ax[1].set_ylim(yl[0],yl[1]) return fig
def test_set_aspect_args(self): axes = Mock() aspect = viz_tools.set_aspect(axes, 3 / 2, adjustable='foo') axes.set_aspect.assert_called_once_with(3 / 2, adjustable='foo') assert aspect == 3 / 2
def surface_maps(carp, grid, stns, ddmmmyy, rdir, humandate, dss_sig): tsal = grid.variables['vosaline'][0, 0, :, :] ttemp = grid.variables['votemper'][0, 0, :, :] tdic = carp.variables['dissolved_inorganic_carbon'][0, 0, :, :] tta = carp.variables['total_alkalinity'][0, 0, :, :] tsra = np.ravel(tsal) ttera = np.ravel(ttemp) ttara = np.ravel(tta) * 1e-3 tdra = np.ravel(tdic) * 1e-3 tzero = np.zeros_like(tsra) tpressure = np.zeros_like(tsra) tpressure[:] = 1 tzero = tpressure * 0 tsra_psu = tsra * 35 / 35.16504 ttera_is = gsw.t_from_CT(tsra, ttera, tzero) response_tup = mocsy.mvars(temp=ttera_is, sal=tsra_psu, alk=ttara, dic=tdra, sil=tzero, phos=tzero, patm=tpressure, depth=tzero, lat=tzero, optcon='mol/m3', optt='Tinsitu', optp='m', optb='l10', optk1k2='m10', optkf='dg', optgas='Pinsitu') pH, pco2, fco2, co2, hco3, co3, OmegaA, OmegaC, BetaD, DENis, p, Tis = response_tup pHr = pH.reshape(898, 398) OmA = OmegaA.reshape(898, 398) surf_dat = [tsal, tdic, tta, ttemp, pHr, OmA] vmins = [25, 1800, 1800, 5, 7.5, 0] vmaxs = [32, 2200, 2200, 15, 8.5, 2] msk = [0, 0, 0, 0, 1e20, 1e20] cl = [ 'salinity psu', 'DIC umol/kg', 'TA umol/kg', 'temp deg C', 'pH', 'Omega A' ] t_cmap = [ cm.cm.haline, cm.cm.matter, cm.cm.matter, cm.cm.thermal, cm.cm.speed, cm.cm.curl ] fig, ((ax1, ax2, ax3), (ax4, ax5, ax6)) = \ plt.subplots(figsize=(20, 27) , nrows=2, ncols=3) viz_tools.set_aspect(ax1) viz_tools.set_aspect(ax2) viz_tools.set_aspect(ax3) viz_tools.set_aspect(ax4) viz_tools.set_aspect(ax5) viz_tools.set_aspect(ax6) i = 0 tplt0 = surf_dat[i] tplt = np.ma.masked_values(tplt0, msk[i]) tcmap = t_cmap[i] mesh = ax1.pcolormesh(tplt, cmap=tcmap, vmin=vmins[i], vmax=vmaxs[i]) cbar = fig.colorbar(mesh, ax=ax1) cbar.set_label(cl[i], fontsize=20) i = 1 tplt0 = surf_dat[i] tplt = np.ma.masked_values(tplt0, msk[i]) tcmap = t_cmap[i] mesh = ax2.pcolormesh(tplt, cmap=tcmap, vmin=vmins[i], vmax=vmaxs[i]) cbar = fig.colorbar(mesh, ax=ax2) cbar.set_label(cl[i], fontsize=20) i = 2 tplt0 = surf_dat[i] tplt = np.ma.masked_values(tplt0, msk[i]) tcmap = t_cmap[i] mesh = ax3.pcolormesh(tplt, cmap=tcmap, vmin=vmins[i], vmax=vmaxs[i]) cbar = fig.colorbar(mesh, ax=ax3) cbar.set_label(cl[i], fontsize=20) i = 3 tplt0 = surf_dat[i] tplt = np.ma.masked_values(tplt0, msk[i]) tcmap = t_cmap[i] mesh = ax4.pcolormesh(tplt, cmap=tcmap, vmin=vmins[i], vmax=vmaxs[i]) cbar = fig.colorbar(mesh, ax=ax4) cbar.set_label(cl[i], fontsize=20) i = 4 tplt0 = surf_dat[i] tplt = np.ma.masked_values(tplt0, msk[i]) tcmap = t_cmap[i] mesh = ax5.pcolormesh(tplt, cmap=tcmap, vmin=vmins[i], vmax=vmaxs[i]) cbar = fig.colorbar(mesh, ax=ax5) cbar.set_label(cl[i], fontsize=20) i = 5 tplt0 = surf_dat[i] tplt = np.ma.masked_values(tplt0, msk[i]) tcmap = t_cmap[i] mesh = ax6.pcolormesh(tplt, cmap=tcmap, vmin=vmins[i], vmax=vmaxs[i]) cbar = fig.colorbar(mesh, ax=ax6) cbar.set_label(cl[i], fontsize=20) cols = [] xs = [] ys = [] stn_in = [] for s in stns: col = stns[s]['color'] x = stns[s]['x'] y = stns[s]['y'] stn = stns[s]['code'] cols.append(col) xs.append(x) ys.append(y) stn_in.append(stn) for w in range(0, len(stns)): pat = patches.Rectangle((xs[w], ys[w]), 20, 20, linewidth=2, edgecolor=cols[w], facecolor='none') ax1.add_patch(pat) for w in range(0, len(cols)): pat = patches.Rectangle((xs[w], ys[w]), 20, 20, linewidth=2, edgecolor=cols[w], facecolor='none') ax2.add_patch(pat) for w in range(0, len(cols)): pat = patches.Rectangle((xs[w], ys[w]), 20, 20, linewidth=2, edgecolor=cols[w], facecolor='none') ax3.add_patch(pat) for w in range(0, len(cols)): pat = patches.Rectangle((xs[w], ys[w]), 20, 20, linewidth=2, edgecolor=cols[w], facecolor='none') ax4.add_patch(pat) for w in range(0, len(cols)): pat = patches.Rectangle((xs[w], ys[w]), 20, 20, linewidth=2, edgecolor=cols[w], facecolor='none') ax5.add_patch(pat) for w in range(0, len(cols)): pat = patches.Rectangle((xs[w], ys[w]), 20, 20, linewidth=2, edgecolor=cols[w], facecolor='none') ax6.add_patch(pat) for i in range(0, len(xs)): ax1.text(xs[i] + 22, ys[i] + 3, stn_in[i], weight='bold', fontsize=20) #tcmap.set_bad('white') st = 'Salish Sea Carbonate Chemistry Map, ' + humandate plt.suptitle(st, fontsize=20) fname = rdir + f'{ddmmmyy}_map_' + dss_sig + '.png' fig.savefig(fname) plt.close()
def map_clusters(tit, no_clusters, cl, fsx, fsy, markersize, titfontsize, legfontsize, fname, colors): """argmuents: map_clusters(tit,no_clusters,cl,fsx,fsy,markersize,titfontsize,legfontsize) cl is list of clusters""" import map_fxn as mf import matplotlib.pyplot as plt import numpy as np import cmocean from salishsea_tools import ( nc_tools, viz_tools, geo_tools, tidetools, visualisations, ) bath = '/data/tjarniko/MEOPAR/NEMO-forcing/grid/mesh_mask_SalishSea2.nc' grid = mf.import_bathy(bath) fmask = (grid.fmask[0, 0, :, :]) spacing = 10 stn_x, stn_y = mf.make_stns(spacing) d_stn_x, d_stn_y = mf.filter_stn_in_domain(stn_x, stn_y, fmask) no_stns = len(d_stn_x) fig = plt.figure(figsize=(fsx, fsy)) plt.rcParams['image.cmap'] = 'YlGnBu' for i in range(1, 2): ax = fig.add_subplot(1, 1, i) viz_tools.set_aspect(ax) fmask = (grid.fmask[0, 0, :, :]) mesh = ax.pcolormesh(fmask, vmin=0, vmax=1) out = ax.set(title='Domain Extent') ax.set_ylim([0, 898]) ax.set_xlim([0, 398]) if i == 1: #colors = plt.cm.hsv(np.linspace(0, 1, no_clusters)) for j in range(1, no_clusters + 1): cluster = np.where(cl == j) cluster = np.squeeze(cluster) #find the xs and ys of the stations in a given cluster c1_x = np.take(d_stn_x, cluster) c1_y = np.take(d_stn_y, cluster) print(j) print(colors[j - 1]) pts = ax.scatter(c1_x, c1_y, s=markersize, c=colors[j - 1], label=j, marker='o') #pts = ax.scatter(c1_x,c1_y,s=markersize,c='xkcd:dust', label=j ,marker='o') ax.set_title(tit, fontsize=titfontsize) ax.set_xticklabels(()) ax.set_yticklabels(()) plt.legend(loc=1, fontsize=legfontsize) plt.savefig(fname, transparent=True) plt.show()