def big_4_raster_plot(title, raster1, raster2, raster3, raster4): fig1, axes1 = plt.subplots(nrows=2, ncols=2, figsize=(16, 12), dpi=80) fig1.suptitle(title) a = axes1[1, 0].imshow(raster1, cmap='pink', interpolation='nearest') ax1_divider = make_axes_locatable(axes1[1, 0]) cax1 = ax1_divider.append_axes('right', size='7%', pad='2%') plt.colorbar(a, cax=cax1) axes1[1, 0].set(title="D") b = axes1[0, 1].imshow(raster2, cmap='viridis') ax2_divider = make_axes_locatable(axes1[0, 1]) cax2 = ax2_divider.append_axes('right', size='7%', pad='2%') plt.colorbar(b, cax=cax2) axes1[0, 1].set(title="canal water level") c = axes1[0, 0].imshow(raster3, cmap='viridis') ax3_divider = make_axes_locatable(axes1[0, 0]) cax3 = ax3_divider.append_axes('right', size='7%', pad='2%') plt.colorbar(c, cax=cax3) axes1[0, 0].set(title="DEM") d = axes1[1, 1].imshow(raster4, cmap='pink') ax4_divider = make_axes_locatable(axes1[1, 1]) cax4 = ax4_divider.append_axes('right', size='7%', pad='2%') plt.colorbar(d, cax=cax4) axes1[1, 1].set(title="elevation - phi")
def main(): from permafrost import draw_regions dm = SweDataManager(var_name="SWE") b, lons2d, lats2d = draw_regions.get_basemap_and_coords() x, y = b(dm.lons2d, dm.lats2d) fig = plt.figure() start_year = 1981 end_year = 1997 levels = [ 10, ] + list(range(20, 120, 20)) + [150, 200, 300, 500, 1000] cmap = mpl.cm.get_cmap(name="jet_r", lut=len(levels)) norm = colors.BoundaryNorm(levels, cmap.N) gs = gridspec.GridSpec(1, 2) ax = fig.add_subplot(gs[0, 0]) data = dm.get_mean(start_year, end_year, months=[3]) img = b.contourf(x, y, data.copy(), ax=ax, cmap=cmap, norm=norm, levels=levels) divider = make_axes_locatable(ax) cax = divider.append_axes("right", "5%", pad="3%") cb = fig.colorbar(img, cax=cax) b.drawcoastlines(ax=ax) ax.set_title("SWE (not interp.), \n DJF period: {0} - {1}".format( start_year, end_year)) ax = fig.add_subplot(gs[0, 1]) data_projected = dm.interpolate_data_to(data, lons2d, lats2d, nneighbours=1) x, y = b(lons2d, lats2d) img = b.contourf(x, y, data_projected, ax=ax, levels=img.levels) # add pretty colorbar divider = make_axes_locatable(ax) cax = divider.append_axes("right", "5%", pad="3%") cb = fig.colorbar(img, cax=cax) b.drawcoastlines(ax=ax) ax.set_title("SWE ( interp.), \n DJF period: {0} - {1}".format( start_year, end_year)) plt.savefig("swe_rb_djf.png") pass
def buildAssessmentGraphs(self): self.qAssessmentFigure = plt.figure() self.qAssessmentFigure.suptitle("Q Assessments") self.qAssessmentGraph = self.qAssessmentFigure.add_subplot(1, 1, 1) divider = make_axes_locatable(self.qAssessmentGraph) self.qAssessmentColorBar = divider.append_axes("right", size="7%", pad="2%") self.policyFigure = plt.figure() self.policyFigure.suptitle("Policy") self.policyGraph = self.policyFigure.add_subplot(1, 1, 1) divider = make_axes_locatable(self.policyGraph) self.policyColorBar = divider.append_axes("right", size="7%", pad="2%")
def __init__(self, ax1, ax2, ax3, imageSeries, extStructFile, options, rotations): self.ax1 = ax1 self.ax2 = ax2 self.ax3 = ax3 self.imageSeries = imageSeries self.options = options self.ind = 0 self.rot = rotations[0] colors = [ 'r', 'g', 'b', 'y', 'c', 'm', 'orange', 'lightcoral', 'peachpuff', 'olive', 'gold', 'navy', 'sienna', 'tan', 'crimson', 'lime', 'goldenrod', 'moccasin', 'beige', 'tomato', 'mistyrose', 'darksalmon', 'navajowhite', 'darkorange', 'snow', 'teal', 'deeppink', 'orchid' ] self.imageSeries = imageSeries self.extStructFile = extStructFile self.structures = self.imageSeries.structures # Has been propagated earlier self.structureColor = {s: c for s, c in zip(self.structures, colors)} if self.extStructFile: self.UIDs = self.extStructFile.getUIDsFromStructures() self.imgList = self.zposList = sorted( self.extStructFile.getZposFromStructures()) self.imageSeries.loadImageFromPosZ(self.zposList[self.ind]) else: self.imgList = self.UIDs = sorted( self.imageSeries.getUIDsFromStructures()) self.imageSeries.loadImageFromUID(self.UIDs[self.ind]) self.imageSeries.resetImage() self.ax1.set_title(imageSeries.amplitude) self.im1 = self.ax1.imshow(self.imageSeries.image, cmap="gray") self.im2 = self.ax2.imshow(self.imageSeries.image, vmin=0, vmax=2, cmap="gray") self.im3 = self.ax3.imshow(self.imageSeries.image, vmin=0, vmax=300) ax2_divider = make_axes_locatable(self.ax2) cax2 = ax2_divider.append_axes("right", size="7%", pad="2%") self.cb2 = plt.colorbar(self.im2, cax=cax2) ax3_divider = make_axes_locatable(self.ax3) cax3 = ax3_divider.append_axes("right", size="7%", pad="2%") self.cb3 = plt.colorbar(self.im3, cax=cax3) self.update()
def plot_ideal_index_distribution(self, obj): if isinstance(obj, OptimizedYJunction): index_calculator = obj.index_calculator elif isinstance(obj, IndexCalculator): index_calculator = obj elif isinstance(obj, BeamPropagator2D): index_calculator = obj.waveguide.index_calc fig, (ax1, ax2) = self.newfig(2, 1, 0.5, 1) x_min, x_max = index_calculator.x[1], index_calculator.x[-2] z_min, z_max = index_calculator.z[1], index_calculator.z[-2] index_real = np.transpose( np.real(index_calculator.ideal_index_distribution)) index_imag = np.transpose( np.imag(index_calculator.ideal_index_distribution)) im_index = ax1.pcolorfast((x_min, x_max), (z_min, z_max), index_real, cmap='magma') im_index_imag = ax2.pcolorfast((x_min, x_max), (z_min, z_max), index_imag, cmap='seismic', vmin=index_imag.min(), vmax=-index_imag.min()) divider = make_axes_locatable(ax1) cax = divider.append_axes("right", size="3%", pad=0.05) cbar = fig.colorbar(im_index, cax=cax) cbar.ax.set_ylabel(r'$\text{Re}(n)$') divider = make_axes_locatable(ax2) cax2 = divider.append_axes("right", size="3%", pad=0.05) cbar2 = fig.colorbar(im_index_imag, cax=cax2) cbar2.ax.set_ylabel(r'$\text{Im}(n)$') #ax1.set_xlabel(" ") ax1.set_ylabel(" ") ax2.set_xlabel(self.x_label) #ax2.set_ylabel(self.z_label) fig.text(0.06, 0.5, self.z_label, ha='center', va='center', rotation='vertical') plt.tight_layout()
def plot_means_and_stds_for_period(year_range=list(range(1981, 2011)), plot_grid=None, row=0, mean_upper_limit=10.0, figure=None, basemap=None, x=None, y=None, mask=None, permafrost_kind_field=None ): """ Calculates fields of means and standard deviations of ALT figure - is the figure to which subplots are added, x, y - 2d coordinates in the basemap projection :type plot_grid: gridspec.GridSpec """ alts = [get_alt_for_year(the_year) for the_year in year_range] mean_alt = np.mean(alts, axis=0) std_alt = np.std(alts, axis=0) mean_alt = np.ma.masked_where(mask, mean_alt) std_alt = np.ma.masked_where(mask, std_alt) alt_levels = list(range(0, int(mean_upper_limit + 1))) cmap = cm.get_cmap("jet", len(alt_levels)) ax0 = figure.add_subplot(plot_grid[row, 0]) cs0 = basemap.contourf(x, y, mean_alt, ax=ax0, levels=alt_levels, cmap=cmap) ax0.set_title("mean over {0} - {1}".format(year_range[0], year_range[-1])) divider = make_axes_locatable(ax0) cax = divider.append_axes("right", "5%", pad="3%") cb = plt.colorbar(cs0, cax=cax) basemap.contour(x, y, permafrost_kind_field, levels=range(1, 4), colors="k", linewidths=0.5, ax=ax0) ax1 = figure.add_subplot(plot_grid[row, 1]) std_alt = np.ma.masked_where(mean_alt > mean_upper_limit, std_alt) cs1 = basemap.contourf(x, y, std_alt, ax=ax1) divider = make_axes_locatable(ax1) cax = divider.append_axes("right", "5%", pad="3%") cb = plt.colorbar(cs1, cax=cax) basemap.contour(x, y, permafrost_kind_field, levels=range(1, 4), colors="k", linewidths=0.5, ax=ax1) ax1.set_title("Interannual variability") # draw coast lines basemap.drawcoastlines(ax=ax1, linewidth=0.5) basemap.drawcoastlines(ax=ax0, linewidth=0.5)
def add_colorbar_right(self): labellen = max(str_len(self.colorbar_fmt % self.valmin), str_len(self.colorbar_fmt % self.valmax)) width = self.fig.get_size_inches()[0] colorbar_len = 8 leg2inch = self.fontsize_cbtick / 144. right_inch = (labellen + colorbar_len) * leg2inch lspace = right_inch / width if (lspace * 0.8) > (1. - lspace): raise ValueError("Plase set arg 'figsize=(width, height)' when using dv_map, and increase width a little.") self.fig.subplots_adjust(left=lspace * 0.8, right=1. - lspace) ax = self.get_main_ax() divider = make_axes_locatable(ax) cbar_width = 0.15 space = cbar_width * 0.8 colorbar_ax = divider.append_axes("right", size=cbar_width, pad=space) norm = mpl.colors.Normalize(vmin=self.valmin, vmax=self.valmax) cb = mpl.colorbar.ColorbarBase(colorbar_ax, cmap=self.colormap, norm=norm, extend=self.colorbar_extend, boundaries=self.colorbar_bounds, ticks=self.colorbar_bounds, orientation='vertical', format=self.colorbar_fmt) # font of colorbar for l in colorbar_ax.yaxis.get_ticklabels(): l.set_fontproperties(self.font) l.set_fontsize(self.fontsize_cbtick) if self.colorbar_unit: cb.ax.set_title(self.colorbar_unit, y=1.01, fontproperties=self.font_leg, fontsize=self.fontsize_label, loc="left") cb.outline.set_linewidth(EDGE_LW)
def plot_image(): plt.figure(2) ax1 = plt.subplot(1, 1, 1) nz, nx = 750, 497 data_fn = "/Users/stone/series-original-model/Marmousi_Model/mar_v_dx12.5m_dz4m_750x497.dat" data = ReadDat(data_fn, shape=[nz, nx]) im1 = plt.imshow(data, cmap=set_cmp) plt.title(set_title, fontsize=16, fontweight='bold') # ------ Add colorbar ------ # step 1 make ax1 locatable ax1_divider = make_axes_locatable(ax1) # step 2 split ax1 for a sub ax to create our colorbar # [location] [width] [distance to image] cax1 = ax1_divider.append_axes("right", size="3%", pad="2%") # step 3 call colorbar! cb1 = plt.colorbar(im1, cax=cax1) plt.show() return
def _plot_depth(data, lons2d, lats2d, basemap=None, clevels=None, lowest_value=0.1, ax=None): if clevels is None: clevels = list(range(-2100, -300, 600)) + list(range( -300, 0, 20)) + list(range(0, 300, 20)) cmap = cm.get_cmap(name="jet_r", lut=len(clevels)) norm = colors.BoundaryNorm(clevels, cmap.N) x, y = basemap(lons2d, lats2d) if lowest_value is not None: mean_level = np.ma.masked_where(np.abs(data) < lowest_value, data) else: mean_level = data #img = basemap.contourf(x, y, mean_level, norm = norm, levels = clevels, cmap = cmap) img = basemap.pcolormesh(x, y, mean_level, norm=norm, cmap=cmap, ax=ax) basemap.drawcoastlines(ax=ax) if ax is None: ax = plt.gca() divider = make_axes_locatable(ax) cax = divider.append_axes("right", "5%", pad="3%") plt.colorbar(img, ax=ax, cax=cax)
def plot_interpolated_field(self, obj): if isinstance(obj, OptimizedYJunction): indexcalculator = obj.index_calc elif isinstance(obj, IndexCalculator): indexcalculator = obj elif isinstance(obj, BeamPropagator2D): indexcalculator = obj.waveguide.index_calc fig, ax = self.newfig(1, 1, 0.5, 1) x_min, x_max = indexcalculator.x[0], indexcalculator.x[-1] z_min, z_max = indexcalculator.z[0], indexcalculator.z[-1] field = np.transpose(np.abs(indexcalculator.interpolated_field)**2) im_field = ax.pcolorfast( (x_min, x_max), (z_min, z_max), field, #norm=colors.SymLogNorm(linthresh=0.03, linscale=0.5, #), cmap='inferno') divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="3%", pad=0.05) cbar = fig.colorbar(im_field, cax=cax) cbar.ax.set_ylabel(r'Field Intensity') ax.set_ylabel(self.z_label) ax.set_xlabel(self.x_label) plt.tight_layout()
def plot_Z(Z_mean, wi_mean, lami_est, w_thresh=.01, cm_greys=plt.cm.get_cmap('Greys', 5), fs_lab=10, add_colorbar=True, fs_cbar=10, fs_w=10, fs_celltypes=10, xlab="markers", ylab="cell subpopulations (abundance)", markernames=[], fs_markers=10, w_digits=1): J = Z_mean.shape[0] k_ord = wi_mean.argsort() z_cols = [] for k in k_ord.tolist(): if wi_mean[k] > w_thresh: z_cols.append(k) z_cols = np.array(z_cols) Z_hat = Z_mean[:, z_cols].T im = plt.imshow(Z_hat, aspect='auto', vmin=0, vmax=1, cmap=cm_greys) plt.xlabel(xlab, fontsize=fs_lab) plt.ylabel(ylab, fontsize=fs_lab) # W percentages w_perc = wi_mean[z_cols] w_perc = [str((wp * 100).round(w_digits)) + '%' for wp in w_perc] ax = plt.gca() # plt.xticks([]) labels = ['{} ({})'.format(zc + 1, wp) for (zc, wp) in zip(z_cols, w_perc)] plt.yticks(np.arange(len(z_cols)), labels, fontsize=fs_celltypes) add_gridlines_Z(Z_hat) plt.xticks(rotation=90, fontsize=fs_markers) if len(markernames) == 0: plt.xticks(np.arange(J), np.arange(J) + 1) else: plt.xticks(np.arange(J), markernames) # add wi_mean on right side # K = z_cols.shape[0] # ax2 = ax.twinx() # ax2.set_yticks(range(K)) # plt.yticks((K-1) / K * np.arange(K) + .5, w_perc[::-1], fontsize=fs_w) # ax2.tick_params(length=0) # colorbar if add_colorbar: ax_divider = make_axes_locatable(ax) cax = ax_divider.append_axes("top", size="7%", pad="2%") cax.xaxis.set_ticks_position("top") cbar = colorbar(im, cax=cax, orientation="horizontal") cbar.ax.tick_params(labelsize=fs_cbar)
def test(): fig = plt.figure() b, lons2d, lats2d = draw_regions.get_basemap_and_coords(llcrnrlat=40.0, llcrnrlon=-145, urcrnrlon=-10) x, y = b(lons2d, lats2d) permafrost_mask = draw_regions.get_permafrost_mask(lons2d, lats2d) dm = CRCMDataManager(data_folder="data/CORDEX") # needed here only for verticla levels h = dm.get_alt_using_files_in(folder="data/CORDEX/na/era40_2") h = np.ma.masked_where((permafrost_mask == 0) | (permafrost_mask >= 3) | (h < 0), h) levels = np.arange(0, 11, 1) ax = plt.gca() img = b.contourf(x, y, h, levels=levels, cmap=cm.get_cmap("jet", len(levels) - 1), ax=ax) # img = b.pcolormesh(x,y, h, vmin = levels[0], vmax = levels[-1]) divider = make_axes_locatable(ax) cax = divider.append_axes("right", "5%", pad="3%") cb = fig.colorbar(img, cax=cax) ax.set_title("ERA40-2 1958-1961") b.drawcoastlines(ax=ax) b.contour(x, y, permafrost_mask, levels=range(1, 4), colors="k", linewidths=0.5, ax=ax) fig.savefig("alt_ERA40-2.png")
def plot_alt_from_monthly_climatologies(): plot_utils.apply_plot_params(width_pt=None, height_cm=20, width_cm=16, font_size=12) figure = plt.figure() b, lons2d, lats2d = draw_regions.get_basemap_and_coords(llcrnrlat=40.0, llcrnrlon=-145, urcrnrlon=-10) x, y = b(lons2d, lats2d) permafrost_mask = draw_regions.get_permafrost_mask(lons2d, lats2d) dm = CRCMDataManager(data_folder="data/CORDEX") year_ranges = [list(range(1981, 1985)), list(range(2041, 2045)), list(range(2071, 2075))] gs = gridspec.GridSpec(len(year_ranges), 1) pf_mask = (permafrost_mask == 1) | (permafrost_mask == 2) pf_mask = ~pf_mask permafrost_mask = np.ma.masked_where(permafrost_mask <= 0, permafrost_mask) for i, year_range in enumerate(year_ranges): ax = figure.add_subplot(gs[i, 0]) alt = dm.get_alt_using_monthly_mean_climatology(year_range) alt = np.ma.masked_where(pf_mask, alt) img = b.contourf(x, y, alt, levels=range(11), cmap=cm.get_cmap("jet", ), ax=ax) divider = make_axes_locatable(ax) cax = divider.append_axes("right", "5%", pad="3%") cb = plt.colorbar(img, cax=cax) b.contour(x, y, permafrost_mask, levels=range(5), linewidth=0.1, colors="k", ax=ax) b.drawcoastlines(ax=ax, linewidth=0.5) ax.set_title("period: {0} - {1}".format(year_range[0], year_range[-1])) plt.savefig("alt_from_clim.png")
def colorbar(mappable, axis, ticks=None, ticklabels=None, boundaries=None, minor=True, unit='kR'): """ Produces a better colorbar than default, making sure that the height of the colorbar matches the height of the axis to which it's attached. Parameters ---------- mappable : object The imshow/meshgrid object with the colored data. axis : Axis The axis to which to attach the colorbar. ticks : int or float list or array Locations of colorbar ticks. ticklabels : str list or array Labels for colorbar ticks. boundaries : array-like The boundaries of discrete ticks (analogous to bin edges). minor : bool Whether or not to display minor ticks on the colorbar. unit : str The unit to display with the highest value on the colorbar. To suppress set to None. Returns ------- cbar : Colorbar The colorbar object. """ # create divider for axis divider = make_axes_locatable(axis) # place a new axis to the right of the existing axis cax = divider.append_axes('right', size='2.5%', pad=0.15) # otherwise, place the colorbar using provided ticks and ticklabels if ticks is not None: cbar = plt.colorbar(mappable, cax=cax, ticks=ticks, boundaries=boundaries) ticklabels = np.array(ticklabels).astype(str) if unit is not None: ticklabels[-1] += ' ' + unit cbar.ax.set_yticklabels(ticklabels) # if no ticks provided, just place the colorbar with built-in tick marks else: cbar = plt.colorbar(mappable, cax=cax, boundaries=boundaries) if minor: cbar.ax.minorticks_on() # return the colorbar return cbar
def plot_time_evolution(arg): fg = plt.figure(figsize=[9.0, 9.0]) ax = fg.add_subplot(111) cax = make_axes_locatable(ax).append_axes('right', size='8%', pad='5%') for i in range(Ni): ax.clear() cax.clear() if (arg == 'f'): clevels = np.linspace(min_f, max_f, 100) # contour plot im = ax.contourf(x1, x2, f[str(i)], clevels, cmap='jet') ax.set_title('Distribution function at t = %i' % i) elif (arg == 'f_ex'): clevels = np.linspace(min_f_ex, max_f_ex, 100) im = ax.contourf(x1, x2, f_ex[str(i)], clevels, cmap='jet') ax.set_title('Exact solution at t = %i' % i) elif (arg == 'error'): clevels = np.linspace(min_err, max_err, 100) im = ax.contourf(x1, x2, e[str(i)], clevels, cmap='jet') ax.set_title('Error on solution at t = %i' % i) # plot grids nr = 16 ax.plot(x1[:, ::nr], x2[:, ::nr], color='lightgrey', lw=0.5) ax.plot(x1.transpose()[:, ::nr], x2.transpose()[:, ::nr], color='lightgrey', lw=0.5) # style ax.set_aspect('equal') fg.colorbar(im, cax=cax) fg.canvas.draw() plt.pause(1.0e-03)
def plot_projs_with_slider(mrcs_files, log_scale=True, show_ac_image=False): for mrcs in mrcs_files: image_stack = mrc.readMRCimgs(mrcs, 0) size = image_stack.shape N = size[0] mask = gen_dense_beamstop_mask(N, 2, 0.003, psize=9) print('image size: {0}x{1}, number of images: {2}'.format(*size)) # plot projections fig = plt.figure(figsize=(8, 8)) gs = GridSpec( 2, 2, width_ratios=[1, 0.075], height_ratios=[1, 0.075], ) # original ax = fig.add_subplot(gs[0, 0]) curr_img = image_stack[:, :, 0] * mask if show_ac_image: curr_ac_img = correlation.calc_full_ac(curr_img, 0.95) * mask curr_img = curr_ac_img if log_scale: curr_img = log(curr_img) im = ax.imshow(curr_img, origin='lower') ticks = [0, int(N / 4.0), int(N / 2.0), int(N / 4.0 * 3), int(N - 1)] ax.set_xticks(ticks) ax.set_yticks(ticks) ax.set_title('Slice Viewer (log scale: {}) for {}'.format( log_scale, os.path.basename(mrcs))) ax_divider = make_axes_locatable(ax) cax = ax_divider.append_axes("right", size="7%", pad="2%") cbar = fig.colorbar(im, cax=cax) # colorbar # slider ax_slider = fig.add_subplot(gs[1, 0]) idx_slider = Slider(ax_slider, 'index:', 0, size[2] - 1, valinit=0, valfmt='%d') def update(val): idx = int(idx_slider.val) curr_img = image_stack[:, :, idx] * mask if show_ac_image: curr_ac_img = correlation.calc_full_ac(curr_img, 0.95) * mask curr_img = curr_ac_img if log_scale: curr_img = log(curr_img) im.set_data(curr_img) cbar.set_clim(vmin=curr_img.min(), vmax=curr_img.max()) cbar.draw_all() fig.canvas.draw_idle() idx_slider.on_changed(update) plt.show()
def make_plot(self,save=False, figtitle=None, pcolormesh_kwargs={}, quiver_kwargs={}): x = self.proj_density/self.proj_density.max() y = self.DOP*100 xtitle = r'$N/N_{max}$' ytitle = r'$P[\%]$' fig, axs = plt.subplots(2, 1, figsize=(5,6), gridspec_kw={ 'height_ratios': [2.5, 1]}) # the 2D plot ax = axs[0] # make axis locatable divider = make_axes_locatable(ax) cax = divider.append_axes("right", size='5%', pad=0) cax_quiver = divider.append_axes("bottom", size='5%', pad=0) # make heatmap plot pcolormesh_kwargs['cmap'] = pcolormesh_kwargs.get('cmap', 'cividis') pc = ax.pcolormesh(self.x_corner,self.x_corner,x, **pcolormesh_kwargs) # make quiver plot default_quiver_kwargs = dict(cmap='RdBu_r', clim=(0,100), headlength=0, pivot='middle', scale=15.,headaxislength=0, headwidth=1) quiveropts = quiver_kwargs.copy() for key, value in default_quiver_kwargs.items(): quiveropts[key] = quiveropts.get(key, value) every = quiveropts.pop('plot_every', None) mask1 = (slice(None,None,every)) mask2 = (slice(None,None,every),slice(None,None,every)) xc = self.x_center[mask1] yc = self.x_center[mask1] I = np.sin(self.offset)[mask2] J = np.cos(self.offset)[mask2] P = y[mask2] qv = ax.quiver(xc,yc,I.T,J.T,P,**quiveropts) # finalizing 2D plot plt.colorbar(pc, cax=cax, ax = ax) plt.colorbar(qv, cax=cax_quiver, ax = ax, orientation='horizontal') ax.set_aspect(1.) ax.tick_params(right= False,top= False,left= False, bottom= False, labelright=False,labeltop=False,labelleft=False,labelbottom=False) ax.set_title(xtitle) # the 1D plot ax = axs[1] ax.semilogy(x.flatten(),y.flatten(),'o',fillstyle='none') ax.set_xlabel(xtitle) ax.set_ylabel(ytitle) # finalizing the figure fig.tight_layout() if save: if figtitle is not None: fig.savefig(figtitle,dpi=300) print ("figure saved, name: {}".format(figtitle)) else: sys.exit("Please define figtitle") else: plt.show()
def plot_total_field(model, yb, ylabel, block=False, ax=None, fig_width=4, cbar=True, cax=None, vmin=1e-3, vmax=1.0): """Plot the total (time-integrated) field over the computatonal domain for a given vowel sample """ with torch.no_grad(): y_tot = torch.abs(yb).pow(2).sum(dim=1) if ax is None: fig, ax = plt.subplots(1, 1, constrained_layout=True, figsize=(1.1 * fig_width, model.Ny / model.Nx * fig_width)) Z = y_tot[0, :, :].numpy().transpose() Z = Z / Z.max() h = ax.imshow(Z, cmap=plt.cm.magma, origin="bottom", norm=mpl.colors.LogNorm(vmin=vmin, vmax=vmax)) if cbar: if cax is None: ax_divider = make_axes_locatable(ax) cax = ax_divider.append_axes("top", size="5%", pad="20%") if vmax < 1.0: extend = 'both' else: extend = 'min' plt.colorbar( h, cax=cax, orientation='horizontal', label= r"$\sum_t{ \left\vert u_t{\left(x,y\right)} \right\vert^2 }$") # cax.set_title(r"$\sum_n \vert u_n \vert^2$") plot_structure(model, ax=ax, outline=True, outline_pml=True, vowel_probe_labels=None, highlight_onehot=ylabel, bg='dark', alpha=0.5) ax.set_xticks([]) ax.set_yticks([]) # ax.annotate(r"$\sum_n \vert u_n \vert^2$", xy=(0.5, 0.01), fontsize="smaller", ha="center", va="bottom", color="w", xycoords="axes fraction") if ax is not None: plt.show(block=block)
def _plot_glm_contrast_topo(inst, contrast, figsize=(12, 7), sphere=None): info = deepcopy(inst if isinstance(inst, Info) else inst.info) # Extract types. One subplot is created per type (hbo/hbr) types = np.unique(_get_channel_types(info)) # Extract values to plot and rescale to uM estimates = contrast.effect[0] estimates = estimates * 1e6 # Create subplots for figures fig, axes = plt.subplots(nrows=1, ncols=len(types), figsize=figsize) # Create limits for colorbar vmax = np.max(np.abs(estimates)) vmin = vmax * -1. cmap = mpl.cm.RdBu_r norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax) for t_idx, t in enumerate(types): estmrg, pos, chs, sphere = _handle_overlaps(info, t, sphere, estimates) # Deal with case when only a single chroma is available if len(types) == 1: ax = axes else: ax = axes[t_idx] # Plot the topomap plot_topomap(estmrg, pos, extrapolate='local', names=chs, vmin=vmin, vmax=vmax, cmap=cmap, axes=ax, show=False, sphere=sphere) # Sets axes title if t == 'hbo': ax.set_title('Oxyhaemoglobin') elif t == 'hbr': ax.set_title('Deoxyhaemoglobin') else: ax.set_title(t) # Create a single colorbar for all types based on limits above ax1_divider = make_axes_locatable(ax) cax1 = ax1_divider.append_axes("right", size="7%", pad="2%") cbar = mpl.colorbar.ColorbarBase(cax1, cmap=cmap, norm=norm, orientation='vertical') cbar.set_label('Contrast Effect', rotation=270) return fig
def setup_axes(): ax = pywcsgrid2.subplot(111, header=co_header) #add colorbar axes divider = make_axes_locatable(ax) cax = divider.new_horizontal("5%", pad=0.1, axes_class=Axes) fig.add_axes(cax) return ax, cax
def add_cbar(self, im, ax): from matplotlib.axes import Axes import pylab as P from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable divider = make_axes_locatable(ax) cax = divider.new_horizontal("5%", pad="2%", axes_class=Axes) self.fig.add_axes(cax) cbar = P.colorbar(im, cax=cax)
def main(): from permafrost import draw_regions dm = SweDataManager(var_name="SWE") b, lons2d, lats2d = draw_regions.get_basemap_and_coords() x, y = b(dm.lons2d, dm.lats2d) fig = plt.figure() start_year = 1981 end_year = 1997 levels = [10, ] + list(range(20, 120, 20)) + [150, 200, 300, 500, 1000] cmap = mpl.cm.get_cmap(name="jet_r", lut=len(levels)) norm = colors.BoundaryNorm(levels, cmap.N) gs = gridspec.GridSpec(1, 2) ax = fig.add_subplot(gs[0, 0]) data = dm.get_mean(start_year, end_year, months=[3]) img = b.contourf(x, y, data.copy(), ax=ax, cmap=cmap, norm=norm, levels=levels) divider = make_axes_locatable(ax) cax = divider.append_axes("right", "5%", pad="3%") cb = fig.colorbar(img, cax=cax) b.drawcoastlines(ax=ax) ax.set_title("SWE (not interp.), \n DJF period: {0} - {1}".format(start_year, end_year)) ax = fig.add_subplot(gs[0, 1]) data_projected = dm.interpolate_data_to(data, lons2d, lats2d, nneighbours=1) x, y = b(lons2d, lats2d) img = b.contourf(x, y, data_projected, ax=ax, levels=img.levels) # add pretty colorbar divider = make_axes_locatable(ax) cax = divider.append_axes("right", "5%", pad="3%") cb = fig.colorbar(img, cax=cax) b.drawcoastlines(ax=ax) ax.set_title("SWE ( interp.), \n DJF period: {0} - {1}".format(start_year, end_year)) plt.savefig("swe_rb_djf.png") pass
def correlation_plot(corr, mesh, label="", title="", sdir=None, context='talk', cmap='jet'): """ plot the correlation function of a pair of 2D arrays (x,y) :param corr: 2D correlation array (via get_correlation) :param mesh: coordinate mesh [np array] :param sdir: save directory for output .png :param label: figure label :param title: figure title :param cmap: figure color map """ #sns.set({'axes.grid' : False}) sns.set_context(context) fig, ax1 = plt.subplots() img = ax1.imshow(corr, cmap=cmap, extent=[ np.min(mesh[1]) * 1e6, np.max(mesh[1]) * 1e6, np.min(mesh[0]) * 1e6, np.max(mesh[0]) * 1e6 ], vmin=0.5, vmax=1.0) fig.suptitle = title divider = make_axes_locatable(ax1) cax = divider.append_axes('right', size='7.5%', pad=0.05) cbar = fig.colorbar(img, cax) cbar.set_label("$g^{(N)}_T$") ax1.set_xlabel("x [$\mu$m]") ax1.set_ylabel("y [$\mu$m]") ax1.annotate(label, horizontalalignment='left', verticalalignment='bottom', xy=(0, 1), c='white') plt.rcParams["axes.grid"] = False if sdir is None: fig.show() else: fig.savefig(sdir) plt.show()
def plot_alt(alt, tmin, tmax, levelheights, annual_means, coordfile="", lon1=-97.0, lat1=47.50, lon2=-7, lat2=0 ): fig = plt.figure() ax = fig.add_subplot(111) basemap, lons2d, lats2d = draw_regions.get_basemap_and_coords(resolution="c", # llcrnrlat=40.0, llcrnrlon=-145, urcrnrlon=-20, urcrnrlat=74, file_path=coordfile, lon1=lon1, lat1=lat1, lon2=lon2, lat2=lat2 ) assert isinstance(basemap, Basemap) lons2d[lons2d > 180] -= 360 x, y = basemap(lons2d, lats2d) permafrost_mask = draw_regions.get_permafrost_mask(lons2d, lats2d) # mask_cond = (permafrost_mask <= 0) | (permafrost_mask >= 3) | (alt < 0) alt = np.ma.masked_where(alt < 0, alt) bounds = [0, 0.1, 0.5, 1, 2, 3, 5, 8, 9, 10, 11] cmap = my_colormaps.get_lighter_jet_cmap(ncolors=10) #cm.get_cmap("jet",10) norm = BoundaryNorm(boundaries=bounds, ncolors=cmap.N, clip=True) qm = basemap.pcolormesh(x, y, alt, cmap=cmap, norm=norm, ax=ax) #qm = basemap.contourf(x, y, alt, levels = bounds, ax = ax) divider = make_axes_locatable(ax) cax = divider.append_axes("right", "5%", pad="3%") cb = fig.colorbar(qm, cax=cax, extend="max", ticks=bounds) basemap.drawcoastlines(ax=ax, linewidth=0.5) #basemap.readshapefile("data/pf_4/permafrost8_wgs84/permaice", name="zone", # ax=ax, linewidth=1.5) basemap.readshapefile("data/permafrost_lat-lon1/permafrost_latlon", name="zone", ax=ax, linewidth=1.5) #crossPlotter = SoundingPlotter(ax, basemap, tmin, tmax, lons2d, lats2d, levelheights=levelheights) sectPlotter = SoundingAndCrossSectionPlotter(ax, basemap, tmin, tmax, lons2d, lats2d, levelheights=levelheights, temporal_data=annual_means) i_inds = [55, 47, 59, 43, 43, 50, 70, 67, 80, 77, 97, 117, 121, 143, 132, 148, 143, 154, 144, 144, 120, 118, 94, 74, 66, 82, 99, 126, 106] j_inds = [79, 89, 94, 104, 114, 122, 123, 139, 134, 149, 145, 152, 141, 135, 133, 106, 57, 55, 40, 35, 39, 49, 53, 63, 54, 46, 44, 69, 59] sectPlotter.plot_cross_sections_for(i_inds, j_inds) plt.show()
def visualize_Q(model): """ Plot the Q values (for both actions) """ # approximation of the state space p_space = [i / 10 for i in range(-10, 11, 1)] s_space = [i / 10 for i in range(-30, 30, 3)] # store the values of the q-functions q_functions = [] for u in [4, -4]: q = [] for s in s_space: q_s = [] for p in p_space: # apply the model for this state/action pair input = np.array([[p, s, u]]) q_s.append(model.predict(input).item()) q.append(q_s) q_functions.append(q) # we want the heatmaps be based on the same heat scale vmin, vmax = np.amin(q_functions), np.amax(q_functions) fig, ax = plt.subplots(1, 2) for i, q in enumerate(q_functions): # plot the q-function as a heatmap heatmap = ax[i].imshow(q) # annotate the axes ax[i].set_xlabel('p') ax[i].set_ylabel('s', rotation=0) ax[i].set_xticks((np.arange(5) / 4) * (np.shape(q)[1] - 1)) ax[i].set_yticks((np.arange(7) / 6) * (np.shape(q)[0] - 1)) ax[i].set_xticklabels([-1, 0.5, 0, 0.5, 1]) ax[i].set_yticklabels([-3, -2, -1, 0, 1, 2, 3]) # make the values of both image fall into the same range norm = colors.Normalize(vmin=vmin, vmax=vmax) heatmap.set_norm(norm) # display the color map above this heatmap divider = make_axes_locatable(ax[i]) cax = divider.append_axes("top", size="7%", pad="2%") colorbar = fig.colorbar(heatmap, cax=cax, orientation='horizontal') cax.xaxis.set_ticks_position("top") fig.suptitle( 'Q-functions : $\hat{Q}_{4}$ in the left and $\hat{Q}_{-4}$ in the right.', fontsize=14) plt.show()
def _plot_choropleth( fig, ax, N, ticks, cmap="Reds", ascending=False, format_prices=False ): """ Internal function to make the choropleth map. """ # Despine the axes sns.despine(ax=ax, bottom=True, top=True, left=True, right=True) # Split and add the colorbar divider = make_axes_locatable(ax) cax = divider.append_axes("bottom", size="5%", pad="7%") fig.add_axes(cax, label="cax") # Plot the city limits as background limits = gv_data.CityLimits.get() limits.buffer(1500).plot( ax=ax, facecolor=palette["sidewalk"], edgecolor=palette["sidewalk"] ) # Plot the choropleth N.plot( column="N", ax=ax, cmap=cmap, edgecolor=palette["dark-gray"], linewidth=0.5, legend=False, vmin=ticks[0], vmax=ticks[-1], zorder=10, ) # Set axes limits xmin, ymin, xmax, ymax = N.total_bounds PAD = 1500 ax.set_xlim(xmin - PAD, xmax + PAD) ax.set_ylim(ymin - PAD, ymax + PAD) # Format the colorbar cbar = plt.colorbar(ax.collections[-1], cax=cax, orientation="horizontal") cbar.set_ticks(ticks) # Format axes labelsize = 8 if format_prices else 9 cbar.ax.tick_params(labelsize=labelsize) cbar.outline.set_edgecolor("black") cbar.outline.set_linewidth(0.5) ax.set_axis_off() # Format prices if format_prices: cbar.set_ticklabels(["$%.0fK" % (np.exp(x) / 1e3) for x in ticks]) return cbar
def __init__(self, width, height, dpi): self.fig = matplotlib.figure.Figure(figsize=(width, height), dpi=dpi) self.axes = self.fig.add_subplot(111) self.fig.subplots_adjust( left=0, right=1, bottom=0, top=1) #leave room for colourbar by curring .right # Start with colourbar hidden self.colorbar_axes = make_axes_locatable(self.axes).append_axes( "right", size="5%", pad="2%") self.colorbar_axes.set_visible(False)
def plot_v_phi(self, v_mod=None, plot_residual=True, return_fig=False): """ Plot the rotation profile. Args: v_mod (Optional[ndarray]): Model v_phi profile to compared to the data. plot_residual (Optional[bool]): If a model is provided, plot the residual at the bottom of the axis. return_fig (Optional[bool]): Return the figure. """ # Imports. import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable # Basic plot. fig, ax = plt.subplots(figsize=(5.5, 3.0)) ax.errorbar(self.rvals, self.v_phi, self.dvphi, color='k', fmt=' ', linewidth=0.8, capsize=1.0, capthick=1.0) ax.set_ylim(ax.get_ylim()[0], ax.get_ylim()[1]) if v_mod is not None: ax.plot(self.rvals, v_mod, color='orangered') ax.set_ylabel(r'${\rm v_{\phi} \quad (m\,s^{-1})}$') ax.set_xlim(self.rvals[0], self.rvals[-1]) # Include a residual box. if v_mod is not None and plot_residual: fig.set_size_inches(5.5, 5.0, forward=True) ax_divider = make_axes_locatable(ax) ax1 = ax_divider.append_axes("bottom", size="40%", pad="2%") ax1.set_xlim(ax.get_xlim()[0], ax.get_xlim()[1]) ax.set_xticks([]) ax1.set_xlabel('Radius (au)') ax1.axhline(0.0, color='orangered', lw=1.0, zorder=-10) ax1.errorbar(self.rvals, self.v_phi - v_mod, self.dvphi, color='k', fmt=' ', linewidth=0.8, capsize=1.0, capthick=1.0) ax1.set_ylabel(r'${\rm v_{\phi} - v_{\rm mod} \quad (m\,s^{-1})}$') else: ax.set_xlabel('Radius (au)') if return_fig: return fig
def draw_colorbar(fig, img, ax=None, boundaries=None, ticks=None): """ Draw a nicely aligned colorbar to the axes ax fig - containing figure img - is the result returned from contourf or pcolormesh """ from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable divider = make_axes_locatable(ax) cax = divider.append_axes("right", "5%", pad="3%") cb = fig.colorbar(img, cax=cax, boundaries=boundaries, ticks=ticks)
def _plot_bicmaps(X_orig_std, best_co_config): # Train model with best config. orig_co_model = SpectralCoclustering(random_state=0, svd_method='arpack') orig_co_model.set_params(**best_co_config) orig_co_model.fit(X_orig_std) orig_co_row_sorted = X_orig_std[np.argsort(orig_co_model.row_labels_), :] orig_co_fit_data = orig_co_row_sorted[:, np.argsort(orig_co_model.column_labels_)] hmap = sns.heatmap( orig_co_fit_data, robust=True, cmap=plt.cm.viridis, fmt='f', vmin=np.min(orig_co_fit_data), vmax=np.max(orig_co_fit_data), cbar=False ) coords = bic_coords(orig_co_model, best_co_config['n_clusters']) for num in coords.index: plt.plot( (coords.loc[num, ['x1', 'x2', 'x2', 'x1', 'x1']]), (coords.loc[num, ['y1', 'y1', 'y2', 'y2', 'y1']]), c='darkred' ) plt.ylabel('Patients') plt.xlabel('Features') plt.yticks([], []) plt.xticks([], []) ax_divider = make_axes_locatable(hmap) cax = ax_divider.append_axes('right', size='3%', pad='2%') colorbar.colorbar( hmap.get_children()[0], cax=cax, orientation='vertical' ) #cax.xaxis.set_label_text('AUC', fontname='Sans') #cax.xaxis.set_label_position('top') cbar_ticks = np.linspace( np.nanmin(orig_co_fit_data), np.nanmax(orig_co_fit_data), 6 ) cax.yaxis.set_ticks(cbar_ticks) cax.yaxis.set_ticklabels([f'{num:.01f}' for num in cbar_ticks]) plt.savefig( '../biclustering/bic_map_original_images.pdf', bbox_inches='tight', transparent=True, dpi=CONFIG.DPI, )
def colorbar(mappable): ############################################## # FROM: # # https://joseph-long.com/writing/colorbars/ # ############################################## """ Adds a colorblar with correct colormap next to subplot axis """ ax = mappable.axes fig = ax.figure divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) return fig.colorbar(mappable, cax=cax)
def do_stats_plots(x, y, basemap, hc, hm, hm2d, permafrost_mask): the_mask = hc.mask | hm2d.mask the_min = np.ma.masked_all(the_mask.shape) the_max = np.ma.masked_all(the_mask.shape) the_std = np.ma.masked_all(the_mask.shape) all_axes = [] all_img = [] gs = gridspec.GridSpec(3, 1) fig = plt.figure() assert isinstance(fig, Figure) ax = fig.add_subplot(gs[0, 0]) the_min[~the_mask] = np.ma.min(hm[:, ~the_mask], axis=0) print(the_min.shape) img = basemap.contourf(x, y, the_min, ax=ax) all_img.append(img) all_axes.append(ax) ax.set_title("Min") ax = fig.add_subplot(gs[1, 0]) the_max[~the_mask] = np.ma.max(hm[:, ~the_mask], axis=0) img = basemap.contourf(x, y, the_max, ax=ax) all_img.append(img) all_axes.append(ax) ax.set_title("Max") ax = fig.add_subplot(gs[2, 0]) the_std[~the_mask] = np.ma.std(hm[:, ~the_mask], axis=0) print(the_std.shape) img = basemap.contourf(x, y, the_std, ax=ax) all_img.append(img) all_axes.append(ax) ax.set_title("Std") for the_ax, the_img in zip(all_axes, all_img): assert isinstance(the_ax, Axes) basemap.drawcoastlines(ax=the_ax, linewidth=0.5) divider = make_axes_locatable(the_ax) cax = divider.append_axes("right", "5%", pad="3%") cb = fig.colorbar(the_img, cax=cax) CS = basemap.contour(x, y, permafrost_mask, levels=[0, 1, 2, 3, 4], ax=the_ax, colors="k", linewidth=5) fig.tight_layout() fig.savefig("alt_b1_stats.png") pass
def correlation_lag_plot(corr, mesh, lag=1, title="", xlabel="", ylabel="", label="", context='talk', cmap='viridis', sdir=None): fig, ax1 = plt.subplots(figsize=[5, 5]) ax1.annotate(label, horizontalalignment='left', verticalalignment='bottom', xy=(0, 1), c='black') rng = corr.shape[-1] - lag for itr in range(0, rng): if itr == 0: lc = corr[:, :, itr, itr + lag] else: lc += corr[:, :, itr, itr + lag] lc /= float(rng) print(np.min(lc)) img = ax1.imshow(lc, cmap=cmap, extent=[ np.min(mesh[1]) * 1e6, np.max(mesh[1]) * 1e6, np.min(mesh[0]) * 1e6, np.max(mesh[0]) * 1e6 ], vmin=0.75, vmax=1.0) divider = make_axes_locatable(ax1) cax = divider.append_axes('right', size='7.5%', pad=0.05) cbar = fig.colorbar(img, cax) cbar.set_label("$g^{(N)}_T$") ax1.set_title(title) ax1.set_xlabel(xlabel) ax1.set_ylabel(ylabel) sns.set_context(context) if sdir is not None: fig.savefig(sdir + "{}.png".format(label))
def pmft_plot(pmft, ax=None): """Helper function to draw 2D PMFT diagram. .. moduleauthor:: Jin Soo Ihm <*****@*****.**> Args: pmft (:class:`freud.pmft.PMFTXY2D`): PMFTXY2D instance. ax (:class:`matplotlib.axes.Axes`): axes object to plot. If :code:`None`, make a new axes and figure object. (Default value = :code:`None`). Returns: :class:`matplotlib.axes.Axes`: axes object with the diagram. """ if not MATPLOTLIB: return None try: from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable from matplotlib.colorbar import Colorbar except ImportError: return None else: # Plot figures if ax is None: fig = Figure() ax = fig.subplots() pmft_arr = np.copy(pmft.PMFT) pmft_arr[np.isinf(pmft_arr)] = np.nan xlims = (pmft.X[0], pmft.X[-1]) ylims = (pmft.Y[0], pmft.Y[-1]) ax.set_xlim(xlims) ax.set_ylim(ylims) ax.xaxis.set_ticks([i for i in range(int(xlims[0]), int(xlims[1]+1))]) ax.yaxis.set_ticks([i for i in range(int(ylims[0]), int(ylims[1]+1))]) ax.set_xlabel(r'$x$') ax.set_ylabel(r'$y$') ax.set_title('PMFT') ax_divider = make_axes_locatable(ax) cax = ax_divider.append_axes("right", size="7%", pad="10%") im = ax.imshow(np.flipud(pmft_arr), extent=[xlims[0], xlims[1], ylims[0], ylims[1]], interpolation='nearest', cmap='viridis', vmin=-2.5, vmax=3.0) cb = Colorbar(cax, im) cb.set_label(r"$k_B T$") return ax
def free_energy_of_formation(db_name, ref_energy): """Computes the free energy of formation.""" db = dataset.connect("sqlite:///{}".format(db_name)) tbl = db["results"] temps = [800, 700, 600, 500, 400, 300, 200, 100] concs = np.arange(0.05, 1, 0.05) all_F = {} c_found = [] for c in concs: statement = "SELECT temperature, energy FROM results WHERE al_conc > {} AND al_conc < {}".format(c-0.01, c+0.01) T = [] U = [] for res in db.query(statement): T.append(res["temperature"]) U.append(res["energy"]/1000.0) comp = {"Al": c, "Zn": 1-c} if not T: continue c_found.append(c) free_eng = CanonicalFreeEnergy(comp) T, U, F = free_eng.get(T, U) for temp, f in zip(list(T), list(F)): if temp not in all_F.keys(): all_F[temp] = [f] else: all_F[temp].append(f) cmap = mpl.cm.copper norm = mpl.colors.Normalize(vmin=np.min(temps), vmax=np.max(temps)) scalar_map = mpl.cm.ScalarMappable(cmap=cmap, norm=norm) scalar_map.set_array(temps) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) concs = np.array(c_found) for T in temps: f_form = np.array(all_F[T]) - concs * ref_energy["Al"] - (1.0-concs)*ref_energy["Zn"] f_form *= mol/kJ f_form = f_form.tolist() f_form.insert(0, 0) f_form.append(0) ax.plot([0.0]+concs.tolist()+[1.0], f_form, color=scalar_map.to_rgba(T), marker="^") ax.set_xlabel("Al concentration") ax.set_ylabel("Free energy of formation (kJ/mol)") ax.spines["right"].set_visible(False) ax.spines["top"].set_visible(False) ax_divider = make_axes_locatable(ax) c_ax = ax_divider.append_axes("top", size="7%", pad="2%") cb = fig.colorbar(scalar_map, orientation="horizontal", cax=c_ax) cb.ax.xaxis.set_ticks_position('top') cb.ax.xaxis.set_label_position('top') cb.set_label("Temperature (K)") plt.show()
def main(): from permafrost import draw_regions dm = CRUDataManager() b, lons2d, lats2d = draw_regions.get_basemap_and_coords() x, y = b(dm.lons2d, dm.lats2d) fig = plt.figure() gs = gridspec.GridSpec(1, 2) ax = fig.add_subplot(gs[0, 0]) data = dm.get_mean(1981, 2009, months=[6, 7, 8]) img = b.contourf(x, y, data.copy(), ax=ax) divider = make_axes_locatable(ax) cax = divider.append_axes("right", "5%", pad="3%") cb = fig.colorbar(img, cax=cax) b.drawcoastlines(ax=ax) ax.set_title("CRU (not interp.), \n JJA period: {0} - {1}".format( 1981, 2009)) ax = fig.add_subplot(gs[0, 1]) data_projected = dm.interpolate_data_to(data, lons2d, lats2d) x, y = b(lons2d, lats2d) img = b.contourf(x, y, data_projected, ax=ax, levels=img.levels) # add pretty colorbar divider = make_axes_locatable(ax) cax = divider.append_axes("right", "5%", pad="3%") cb = fig.colorbar(img, cax=cax) b.drawcoastlines(ax=ax) ax.set_title("CRU ( interp.), \n JJA period: {0} - {1}".format(1981, 2009)) plt.show() plt.savefig("t_cru_jja.png") pass
def main(): from permafrost import draw_regions dm = CRUDataManager() b, lons2d, lats2d = draw_regions.get_basemap_and_coords() x, y = b(dm.lons2d, dm.lats2d) fig = plt.figure() gs = gridspec.GridSpec(1, 2) ax = fig.add_subplot(gs[0, 0]) data = dm.get_mean(1981, 2009, months=[6, 7, 8]) img = b.contourf(x, y, data.copy(), ax=ax) divider = make_axes_locatable(ax) cax = divider.append_axes("right", "5%", pad="3%") cb = fig.colorbar(img, cax=cax) b.drawcoastlines(ax=ax) ax.set_title("CRU (not interp.), \n JJA period: {0} - {1}".format(1981, 2009)) ax = fig.add_subplot(gs[0, 1]) data_projected = dm.interpolate_data_to(data, lons2d, lats2d) x, y = b(lons2d, lats2d) img = b.contourf(x, y, data_projected, ax=ax, levels=img.levels) # add pretty colorbar divider = make_axes_locatable(ax) cax = divider.append_axes("right", "5%", pad="3%") cb = fig.colorbar(img, cax=cax) b.drawcoastlines(ax=ax) ax.set_title("CRU ( interp.), \n JJA period: {0} - {1}".format(1981, 2009)) plt.show() plt.savefig("t_cru_jja.png") pass
def plot_all(cv_current, cv_future): plot_utils.apply_plot_params(width_pt=None, font_size=9) fig = plt.figure() ps = map_parameters.polar_stereographic x = ps.lons y = ps.lats basemap = Basemap(projection="npstere", boundinglat = 20, lon_0=-115) [x, y] = basemap(x, y) x_min, x_max = x.min(), x.max() y_min, y_max = y.min(), y.max() all_axes = [] all_images = [] gs = gridspec.GridSpec(2,2) ax1 = fig.add_subplot(gs[0,0]) all_axes.append(ax1) ax1.set_title("SST: CV current") image = basemap.pcolormesh(x, y, cv_current, ax = ax1) all_images.append(image) ax2 = fig.add_subplot(gs[0, 1]) all_axes.append(ax2) ax2.set_title("SST: CV future") image = basemap.pcolormesh(x, y, cv_current, ax = ax2) all_images.append(image) ax3 = fig.add_subplot(gs[1, :]) all_axes.append(ax3) ax3.set_title("SST: CV future - CV current") cMap = my_colormaps.get_red_blue_colormap(ncolors=10) image = basemap.pcolormesh(x, y, cv_future - cv_current, ax = ax3, cmap = cMap, vmin = -0.004, vmax = 0.004 ) all_images.append(image) for the_ax, image in zip( all_axes, all_images): divider = make_axes_locatable(the_ax) the_ax.set_xlim(x_min, x_max) the_ax.set_ylim(y_min, y_max) cax = divider.append_axes("right", "8%", pad="3%") cb = fig.colorbar(image, cax = cax, ax = the_ax) cb.outline.set_visible(False) basemap.drawcoastlines(ax = the_ax) fig.tight_layout() fig.savefig("crcm4_sst_cv.png")
def main(): AFRIC = 1 QUEBEC = 2 varname = "drainage_density" region = QUEBEC if region == QUEBEC: data_path = "/home/huziy/skynet3_rech1/Netbeans Projects/Java/DDM/directions_with_drainage_density/directions_qc_dx0.1deg_5.nc" out_path = "qc_{0}_0.1deg.pdf".format(varname) elif region == AFRIC: data_path = "/home/huziy/skynet3_rech1/Netbeans Projects/Java/DDM/directions_africa_dx0.44deg.v3.nc" out_path = "af_{0}_0.44deg.pdf".format(varname) else: raise Exception("Unknown region...") # ds = Dataset(data_path) data = ds.variables[varname][20:-20, 20:-20] lons = ds.variables["lon"][20:-20, 20:-20] lats = ds.variables["lat"][20:-20, 20:-20] slope = ds.variables["slope"][20:-20, 20:-20] fig = plt.figure() print(data.min(), data.max()) ax = plt.gca() data = np.ma.masked_where(slope < 0, data) basemap = Crcm5ModelDataManager.get_rotpole_basemap_using_lons_lats(lons2d=lons, lats2d=lats) lons[lons > 180] -= 360 x, y = basemap(lons, lats) data = maskoceans(lons, lats, data, inlands=False) img = basemap.contourf(x, y, data, cmap=cm.get_cmap("jet", 10)) ax.set_title("Drainage density") divider = make_axes_locatable(ax) cax = divider.append_axes("right", "5%", pad="3%") cb = fig.colorbar(img, cax=cax) cax.set_title("(km**-1)") basemap.drawcoastlines(ax=ax) fig.tight_layout() fig.savefig(out_path)
def do_stats_plots(x,y,basemap, hc, hm, hm2d, permafrost_mask): the_mask = hc.mask | hm2d.mask the_min = np.ma.masked_all(the_mask.shape) the_max = np.ma.masked_all(the_mask.shape) the_std = np.ma.masked_all(the_mask.shape) all_axes = [] all_img = [] gs = gridspec.GridSpec(3,1) fig = plt.figure() assert isinstance(fig, Figure) ax = fig.add_subplot(gs[0,0]) the_min[~the_mask] = np.ma.min(hm[:,~the_mask], axis=0) print(the_min.shape) img = basemap.contourf(x,y, the_min, ax = ax) all_img.append(img) all_axes.append(ax) ax.set_title("Min") ax = fig.add_subplot(gs[1,0]) the_max[~the_mask] = np.ma.max(hm[:,~the_mask], axis=0) img = basemap.contourf(x,y, the_max, ax = ax) all_img.append(img) all_axes.append(ax) ax.set_title("Max") ax = fig.add_subplot(gs[2,0]) the_std[~the_mask] = np.ma.std(hm[:,~the_mask], axis=0) print(the_std.shape) img = basemap.contourf(x,y, the_std, ax = ax) all_img.append(img) all_axes.append(ax) ax.set_title("Std") for the_ax, the_img in zip( all_axes, all_img ): assert isinstance(the_ax, Axes) basemap.drawcoastlines(ax = the_ax, linewidth=0.5) divider = make_axes_locatable(the_ax) cax = divider.append_axes("right", "5%", pad="3%") cb = fig.colorbar(the_img, cax = cax) CS = basemap.contour(x,y, permafrost_mask, levels = [0,1,2,3,4], ax = the_ax, colors = "k", linewidth= 5) fig.tight_layout() fig.savefig("alt_b1_stats.png") pass
def main(): AFRIC = 1 QUEBEC = 2 region = AFRIC if region == QUEBEC: data_path = "/home/huziy/skynet3_rech1/Netbeans Projects/Java/DDM/directions_with_drainage_density/directions_qc_dx0.1deg_5.nc" out_path = "qc_acc_area_0.1deg.pdf" elif region == AFRIC: data_path = "/home/huziy/skynet3_rech1/Netbeans Projects/Java/DDM/directions_africa_dx0.44deg.v3.nc" out_path = "af_acc_area_0.44deg.pdf" else: raise Exception("Unknown region...") # varname = "accumulation_area" ds = Dataset(data_path) data = ds.variables[varname][30:-30, 30:-30] lons = ds.variables["lon"][30:-30, 30:-30] lats = ds.variables["lat"][30:-30, 30:-30] slope = ds.variables["slope"][30:-30, 30:-30] fig = plt.figure() print(data.min(), data.max()) ax = plt.gca() data = np.ma.masked_where(slope < 0, data) basemap = get_omerc_basemap_africa1(lons, lats) lons[lons > 180] -= 360 x, y = basemap(lons, lats) data = maskoceans(lons, lats, data, inlands=False) img = basemap.contourf(x, y, np.ma.log(data), cmap=cm.get_cmap("winter_r")) divider = make_axes_locatable(ax) cax = divider.append_axes("right", "5%", pad="3%") cb = fig.colorbar(img, cax=cax) cax.set_title("$\ln\left({\\rm km^2 }\\right)$ \n") basemap.drawcoastlines(ax=ax) fig.tight_layout() fig.savefig(out_path)
def main(): path = "/home/huziy/skynet1_rech3/cordex/NorthAmerica_0.44deg_ERA40-Int_195801_static_data.rpn" sim_data_folder = "/home/huziy/skynet1_rech3/cordex/CORDEX_DIAG/era40_driven_b1" #for coordinates coord_file = os.path.join(sim_data_folder, "pmNorthAmerica_0.44deg_ERA40-Int_B1_200812_moyenne") basemap, lons2d, lats2d = draw_regions.get_basemap_and_coords(resolution="c", file_path = coord_file, llcrnrlat=40.0, llcrnrlon=-143, urcrnrlon=-20, urcrnrlat=74 ) #read depth to bedrock field rObj = RPN(path) dpth_to_bdrck = rObj.get_first_record_for_name("8L") rObj.close() #dpth_to_bdrck[:,:] = 4 bounds = [0,0.5,1,1.5,2,2.5,3,3.5,4,4.6] cmap = my_colormaps.get_lighter_jet_cmap(ncolors=len(bounds) - 1) norm = BoundaryNorm(boundaries=bounds, ncolors=cmap.N) x,y = basemap(lons2d, lats2d) fig = plt.figure() CS = basemap.pcolormesh(x, y, dpth_to_bdrck, norm = norm, cmap = cmap) print(( dpth_to_bdrck.min(), dpth_to_bdrck.max())) basemap.drawcoastlines() basemap.drawparallels(np.arange(-80.,81.,20.)) basemap.drawmeridians(np.arange(-180.,181.,20.)) divider = make_axes_locatable(plt.gca()) cax = divider.append_axes("right", "5%", pad="3%") cax.set_title("m") fig.colorbar(CS, cax = cax, ticks=bounds) fig.tight_layout() fig.savefig("dpth_to_bdrck.png") plt.show() pass
def plot_for_scenario(scen_id, ax, basemap=None, x=None, y=None, alt=None, permafrost_mask=None, start_year=None, end_year=None ): """ """ levels = np.arange(0, 11, 1) img = basemap.contourf(x, y, alt, ax=ax, levels=levels, cmap=cm.get_cmap("jet", len(levels) - 1)) # img = b.pcolormesh(x,y, h, vmin = levels[0], vmax = levels[-1]) divider = make_axes_locatable(ax) cax = divider.append_axes("right", "5%", pad="3%") cb = plt.colorbar(img, cax=cax) ax.set_title("{0}: {1}-{2}".format(scen_id, start_year, end_year)) basemap.drawcoastlines(ax=ax) basemap.contour(x, y, permafrost_mask, ax=ax, levels=range(1, 4), colors="k", linewidths=0.5)
def main(): figure = plt.figure() basemap, lons2d, lats2d = get_basemap_and_coords() lons2d[lons2d > 180] -= 360 x0, y0 = basemap(lons2d, lats2d) dx = x0[1, 0] - x0[0, 0] dy = y0[0, 1] - y0[0, 0] x1 = x0 - dx / 2.0 y1 = y0 - dy / 2.0 permafrost_kind_field = get_permafrost_mask(lons2d, lats2d) cmap = ListedColormap(["r", "b", "y", "c"]) cmap.set_over("w") cmap.set_under("w") # permafrost_kind_field = np.ma.masked_where(permafrost_kind_field == 0, permafrost_kind_field) ax_map = plt.gca() # img = basemap.pcolormesh(x1, y1, permafrost_kind_field, ax = ax_map, vmin = 0.5, vmax = 4.5, cmap = cmap ) permafrost_kind_field = maskoceans(lons2d, lats2d, permafrost_kind_field) img = basemap.contourf(x0, y0, permafrost_kind_field, levels=np.arange(0.5, 5, 0.5), cmap=cmap) divider = make_axes_locatable(ax_map) cax = divider.append_axes("bottom", "5%", pad="3%") cb = plt.colorbar(img, ticks=MultipleLocator(), cax=cax, orientation="horizontal") basemap.contour(x0, y0, permafrost_kind_field, ax=ax_map, levels=list(range(6)), linewidths=0.5, colors="k") basemap.drawcoastlines(ax=ax_map) plt.savefig("test.png") # gdal.Dataset. # TODO: implement pass
def _plot_depth(data, lons2d, lats2d, basemap = None, clevels = None, lowest_value = 0.1, ax = None): if clevels is None: clevels = list(range(-2100, -300, 600)) + list(range(-300, 0, 20)) + list(range(0, 300, 20)) cmap = cm.get_cmap(name="jet_r", lut = len(clevels)) norm = colors.BoundaryNorm(clevels, cmap.N) x, y = basemap(lons2d, lats2d) if lowest_value is not None: mean_level = np.ma.masked_where(np.abs(data) < lowest_value, data) else: mean_level = data #img = basemap.contourf(x, y, mean_level, norm = norm, levels = clevels, cmap = cmap) img = basemap.pcolormesh(x,y, mean_level, norm = norm, cmap = cmap, ax = ax) basemap.drawcoastlines(ax=ax) if ax is None: ax = plt.gca() divider = make_axes_locatable(ax) cax = divider.append_axes("right", "5%", pad="3%") plt.colorbar(img, ax = ax, cax = cax)
elif 'horizon' in opts.data: title = r'Horizon Source, ' + title elif 'noise' in opts.data: title = r'Noise Sky, RMS = %.1e, ' %rms + title else: title = r'Nsources: %d, ' %nsources + title fig.suptitle(title) gs.tight_layout(fig) # gs.update(top=0.8, wspace=0.25) gs.update(left = 0.05, right = 0.95, wspace = 0.5, top = 0.9) if opts.force_lim: # Append master colorbar gs.update(right = 0.95) ax_divider = make_axes_locatable(rms_ax) cbar_ax = ax_divider.append_axes("right", size="5%", pad="2%") cb = fig.colorbar(imgs[0], cax=cbar_ax) cb.set_clim(vmin, vmax) if opts.log_scale: cb.set_label('Log Visibilities', size=fontsize, labelpad=10) else: cb.set_label('Visibilities', size=fontsize, labelpad=10) cb.ax.tick_params(labelsize=fontsize) else: for i,ax in enumerate(fig.axes): ax_divider = make_axes_locatable(ax) cax = ax_divider.append_axes("right", size="5%", pad="2%") cb = fig.colorbar(imgs[i], cax=cax)
def plot_alt_from_recent_jpp_and_andrey(): driver = "CanESM" path = "/home/huziy/skynet1_rech3/jpp_progs_recent/pf/Arctic_Andrey_ALT_canesm1" rObj = RPN(path) altt = rObj.get_all_time_records_for_name(varname="FALT") alt = np.mean( np.array(list(altt.values())), axis = 0) rObj.close() coord_file = path basemap, lons2d, lats2d = draw_regions.get_basemap_and_coords(resolution="c", file_path = coord_file, lon1 = 60, lat1 = 89.999, lon2 = -30, lat2 = 0.00001, projection = "omerc", round = True ) assert isinstance(basemap, Basemap) lons2d[lons2d > 180] -= 360 x, y = basemap(lons2d, lats2d) #permafrost_mask = draw_regions.get_permafrost_mask(lons2d, lats2d) #mask_cond = (permafrost_mask <= 0) | (permafrost_mask >= 3) alt = np.ma.masked_where(alt < 0, alt) fig = plt.figure() assert isinstance(fig, Figure) h_max = 10 bounds = list(range(6)) cmap = my_colormaps.get_lighter_jet_cmap(ncolors=len(bounds) - 1) #cm.get_cmap("jet",10) #bounds = [0,0.1,0.5,1,2,3,5,8,9,10,11] norm = BoundaryNorm(boundaries=bounds,ncolors=len(bounds)-1, clip = False) #norm = None cmap.set_over(cmap(1.0)) clevels = np.arange(0,h_max+1,1) gs = gridspec.GridSpec(1,1) #ax = fig.add_axes([0,0,1,1], polar = True) ax = fig.add_subplot(gs[0,0]) assert isinstance(ax, Axes) #hc = np.ma.masked_where(mask_cond | (np.min(altt.values(), axis = 0) < 0), alt) #hc = np.ma.masked_where( (hc < 0), hc) img = basemap.pcolormesh(x, y, alt, cmap = cmap, vmax = h_max, norm=norm) ax.set_title("ALT, JPP-Andrey, ({0} - CRCM5) \n".format(driver)) basemap.drawcoastlines(ax = ax, linewidth=0.5) #basemap.readshapefile("data/pf_4/permafrost8_wgs84/permaice", name="zone", # ax=ax, linewidth=1.5) basemap.readshapefile("data/permafrost_lat-lon1/permafrost_latlon", name="zone", ax=ax, linewidth=1.5) divider = make_axes_locatable(ax) cax = divider.append_axes("right", "5%", pad="3%") cb = fig.colorbar(img, cax = cax, extend = "max", ticks = bounds) cax.set_title("m \n") fig.tight_layout(w_pad=0.0) fig.savefig("alt_jpp_current_{0}.png".format(driver))
def plot_lake_fraction_field(): folder = "/home/huziy/skynet3_rech1/geof_lake_infl_exp" fName = "geophys_Quebec_0.1deg_260x260_with_dd_v6" path = os.path.join(folder, fName) rObj = RPN(path) lkf = rObj.get_first_record_for_name_and_level(varname="VF", level=3, level_kind=level_kinds.ARBITRARY) proj_params = rObj.get_proj_parameters_for_the_last_read_rec() lons2d, lats2d = rObj.get_longitudes_and_latitudes_for_the_last_read_rec() lons2d[lons2d >= 180] -= 360 rObj.close() rll = RotatedLatLon(**proj_params) margin = 20 lons2d = lons2d[margin:-margin, margin:-margin] lats2d = lats2d[margin:-margin, margin:-margin] lkf = lkf[margin:-margin, margin:-margin] basemap = rll.get_basemap_object_for_lons_lats(lons2d=lons2d, lats2d=lats2d, resolution="l") x, y = basemap(lons2d, lats2d) fig = plt.figure() gs = GridSpec(1, 2, width_ratios=[1, 1]) ax = fig.add_subplot(gs[0, 0]) df = 0.1 levels = np.arange(0, 1.1, df) cMap = get_cmap("gist_ncar_r", len(levels) - 1) bn = BoundaryNorm(levels, cMap.N) basemap.drawmapboundary(fill_color="0.75") lkf_plot = maskoceans(lons2d, lats2d, lkf, inlands=False) print("Percentage of lakes in the sim domain: {}".format(lkf_plot.mean() * 100)) img = basemap.pcolormesh(x, y, lkf_plot, norm=bn, cmap=cMap) basemap.drawcoastlines() divider = make_axes_locatable(ax) cax = divider.append_axes("bottom", "5%", pad="3%") cb = fig.colorbar(img, cax=cax, ticks=levels, orientation="horizontal") ax = fig.add_subplot(gs[0, 1]) df1 = df levels1 = np.arange(0, 1.1, df1) cell_numms = np.zeros((len(levels1) - 1,)) left = levels[0] right = levels[1] lefts = [] rights = [] lkf_land = lkf[lkf > 0.01] for i in range(len(cell_numms)): cell_numms[i] = ((lkf_land > left) & (lkf_land <= right)).astype(int).sum() lefts.append(left) rights.append(right) left += df1 right += df1 assert isinstance(ax, Axes) ax.bar(lefts, cell_numms, width=df1) # ax.semilogy(rights, cell_numms) ax.xaxis.set_ticks(levels) ax.yaxis.set_ticks(np.arange(1000, 10000, 1000)) sf = ScalarFormatter(useMathText=True) sf.set_powerlimits([-2, 1]) ax.yaxis.set_major_formatter(sf) ax.grid("on") ax.set_xlabel("fraction") ax.set_ylabel("# gridcells") plt.show() fig.tight_layout() fig.savefig("lake_fractions_220x220_0.1deg.jpeg") plt.show() pass
def plot_current_alts_nyear_rule(nyear = 2): start_year = 1981 end_year = 2008 sim_data_folder = "/home/huziy/skynet1_rech3/cordex/CORDEX_DIAG/era40_driven_b1" sim_names = ["ERA40", "MPI","CanESM"] all_data_f = "/home/huziy/skynet1_rech3/cordex/for_Samira" simname_to_path = { "ERA40": os.path.join(all_data_f, "alt_era_b1_yearly.nc"), "MPI": os.path.join(all_data_f, "alt_mpi_b1_yearly.nc"), "CanESM": os.path.join(all_data_f, "alt_canesm_b1_yearly.nc") } coord_file = os.path.join(sim_data_folder, "pmNorthAmerica_0.44deg_ERA40-Int_B1_200812_moyenne") basemap, lons2d, lats2d = draw_regions.get_basemap_and_coords(resolution="c", file_path = coord_file, llcrnrlat=40.0, llcrnrlon=-145, urcrnrlon=-20, urcrnrlat=74 ) assert isinstance(basemap, Basemap) #basemap.transform_scalar() #basemap = Basemap() lons2d[lons2d > 180] -= 360 x, y = basemap(lons2d, lats2d) #x = (x[1:,1:] + x[:-1, :-1]) /2.0 permafrost_mask = draw_regions.get_permafrost_mask(lons2d, lats2d) mask_cond = (permafrost_mask <= 0) | (permafrost_mask >= 3) # plot_utils.apply_plot_params(width_pt=None, width_cm=20, height_cm=40, font_size=25) fig = plt.figure() assert isinstance(fig, Figure) h_max = 10 cmap = my_colormaps.get_lighter_jet_cmap(ncolors=10) #cm.get_cmap("jet",10) bounds = [0,0.1,0.5,1,2,3,5,8,9,10,11] norm = BoundaryNorm(boundaries=bounds,ncolors=len(bounds), clip=True) cmap.set_over(cmap(1.0)) clevels = np.arange(0,h_max+1,1) gs = gridspec.GridSpec(3,1) all_axes = [] all_img = [] i = 0 hc_list = [] hct_list = [] for name in sim_names: path = simname_to_path[name] #select data and needed alt ds = Dataset(path) years = ds.variables["year"][:] hct = ds.variables["alt"][(years >= start_year) & (years <= end_year),:,:] hct_list.append(hct) print("hct.shape = ", hct.shape) #hc = get_alt_using_nyear_rule(hct, nyears = nyear) hc = np.mean(hct, axis = 0) hc_list.append(hc) ax = fig.add_subplot(gs[i,0]) assert isinstance(ax, Axes) hc = np.ma.masked_where(mask_cond | (np.min(hct, axis = 0) < 0), hc) #hc = np.ma.masked_where( (hc < 0), hc) img = basemap.pcolormesh(x, y, hc, cmap = cmap, vmax = h_max, norm=norm) if not i: ax.set_title("ALT, mean ({0} - {1}) \n".format(start_year, end_year)) i += 1 ax.set_ylabel(name) all_axes.append(ax) all_img.append(img) i = 0 axs_to_hide = [] #zones and coastlines for the_ax, the_img in zip(all_axes, all_img): assert isinstance(the_ax, Axes) basemap.drawcoastlines(ax = the_ax, linewidth=0.5) basemap.readshapefile("data/pf_4/permafrost8_wgs84/permaice", name="zone", ax=the_ax, linewidth=1.5) divider = make_axes_locatable(the_ax) cax = divider.append_axes("right", "5%", pad="3%") cb = fig.colorbar(the_img, cax = cax, extend = "max", ticks = bounds) cax.set_title("m \n") if i != 2: axs_to_hide.append(cax) i += 1 fig.tight_layout(w_pad=0.0) for the_ax in axs_to_hide: the_ax.set_visible(False) fig.savefig("alt_mean_current.png") #print ALT for selected points site_names = ["S","K","T"] sel_lons = [-75.646, -65.92, -69.95] sel_lats = [62.197, 58.709, 58.67] xo,yo,zo = lat_lon.lon_lat_to_cartesian(sel_lons, sel_lats) xi, yi, zi = lat_lon.lon_lat_to_cartesian(lons2d.flatten(), lats2d.flatten()) ktree = KDTree(list(zip(xi,yi,zi))) dists, indexes = ktree.query(list(zip(xo,yo,zo))) for name, data, the_hct in zip(sim_names, hc_list, hct_list): print(name) flat_data = data.flatten() for p_name, ind in zip(site_names, indexes): in_data = [] for t in range(the_hct.shape[0]): in_data.append(the_hct[t,:,:].flatten()[ind]) print(",".join(["{0:.1f}".format(float(x)) for x in in_data])) print(p_name, "{0:.1f} m".format(float(flat_data[ind]))) print("--" * 10)
def plot_future_alts(): start_year = 2041 end_year = 2070 sim_data_folder = "/home/huziy/skynet1_rech3/cordex/CORDEX_DIAG/era40_driven_b1" sim_names = ["MPI","CanESM"] simname_to_path = { "MPI": "/home/huziy/skynet1_rech3/cordex/CORDEX_DIAG/NorthAmerica_0.44deg_MPI_B1", "CanESM": "/home/huziy/skynet1_rech3/cordex/CORDEX_DIAG/NorthAmerica_0.44deg_CanESM_B1" } coord_file = os.path.join(sim_data_folder, "pmNorthAmerica_0.44deg_ERA40-Int_B1_200812_moyenne") basemap, lons2d, lats2d = draw_regions.get_basemap_and_coords(resolution="c", file_path = coord_file, llcrnrlat=40.0, llcrnrlon=-145, urcrnrlon=-20, urcrnrlat=74, anchor="W" ) assert isinstance(basemap, Basemap) #basemap.transform_scalar() #basemap = Basemap() lons2d[lons2d > 180] -= 360 x, y = basemap(lons2d, lats2d) #x = (x[1:,1:] + x[:-1, :-1]) /2.0 permafrost_mask = draw_regions.get_permafrost_mask(lons2d, lats2d) mask_cond = (permafrost_mask <= 0) | (permafrost_mask >= 3) plot_utils.apply_plot_params(width_pt=None, width_cm=25,height_cm=35, font_size=16) fig = plt.figure() assert isinstance(fig, Figure) h_max = 10 cmap = cm.get_cmap("cool",10) cmap.set_over(cmap(1.0)) clevels = np.arange(0,h_max+1,1) gs = gridspec.GridSpec(3,1) all_axes = [] all_img = [] i = 0 for name in sim_names: path = simname_to_path[name] dm = CRCMDataManager(data_folder=path) hc = dm.get_alt_using_monthly_mean_climatology(range(start_year,end_year+1)) ax = fig.add_subplot(gs[i+1,0]) assert isinstance(ax, Axes) hc = np.ma.masked_where(mask_cond, hc) img = basemap.pcolormesh(x, y, hc, cmap = cmap, vmax = h_max) if not i: ax.set_title("ALT from climatology ({0} - {1})".format(start_year, end_year)) i += 1 ax.set_ylabel(name) all_axes.append(ax) all_img.append(img) i = 0 axs_to_hide = [] #zones and coastlines for the_ax, the_img in zip(all_axes, all_img): divider = make_axes_locatable(the_ax) cax = divider.append_axes("right", "5%", pad="3%") cb = fig.colorbar(the_img, cax = cax, extend = "max") assert isinstance(the_ax, Axes) basemap.drawcoastlines(ax = the_ax, linewidth=0.5) basemap.readshapefile("data/pf_4/permafrost8_wgs84/permaice", name="zone", ax=the_ax, linewidth=1.5) if i: axs_to_hide.append(cax) i += 1 #draw zones ax = fig.add_subplot(gs[0,0]) basemap.drawcoastlines(ax = ax, linewidth=1.5) shp_info = basemap.readshapefile("data/pf_2/permafrost5_wgs84/permaice", name="zone", ax=ax, linewidth=3) print(shp_info) for nshape,seg in enumerate(basemap.zone): the_color = "green" if basemap.zone_info[nshape]["EXTENT"] == "C" else "red" poly = mpl.patches.Polygon(seg,facecolor=the_color, zorder = 10) ax.add_patch(poly) b1 = ax.bar([0],[0],color="green", label="Continuous") b2 = ax.bar([0],[0],color="r", label="Discontinuous") ax.legend(loc = "lower left") divider = make_axes_locatable(ax) cax = divider.append_axes("right", "5%", pad="3%") cb = fig.colorbar(all_img[0], cax = cax, extend = "max") axs_to_hide.append(cax) fig.tight_layout() for the_ax in axs_to_hide: the_ax.set_visible(False) fig.savefig("alt_from_climatology_future.png")
def main(): start_year = 1981 end_year = 2008 #mean alt path_to_yearly = "alt_era_b1_yearly.nc" ds = Dataset(path_to_yearly) hm = ds.variables["alt"][:] years = ds.variables["year"][:] years_sel = np.where(( start_year <= years ) & (years <= end_year))[0] print(years_sel) hm = hm[np.array(years_sel),:,:] print(hm.shape) good_points = ~np.any(hm < 0, axis = 0) hm2d = np.ma.masked_all(good_points.shape) hm2d[good_points] = np.mean( hm[ : , good_points], axis = 0) #alt from climatology sim_data_folder = "/home/huziy/skynet1_rech3/cordex/CORDEX_DIAG/era40_driven_b1" # dm = CRCMDataManager(data_folder=sim_data_folder) # hc = dm.get_alt_using_monthly_mean_climatology(xrange(start_year,end_year+1)) coord_file = os.path.join(sim_data_folder, "pmNorthAmerica_0.44deg_ERA40-Int_B1_200812_moyenne") basemap, lons2d, lats2d = draw_regions.get_basemap_and_coords(resolution="c", file_path = coord_file, llcrnrlat=40.0, llcrnrlon=-145, urcrnrlon=-20, urcrnrlat=74 ) assert isinstance(basemap, Basemap) #basemap.transform_scalar() #basemap = Basemap() lons2d[lons2d > 180] -= 360 x, y = basemap(lons2d, lats2d) #x = (x[1:,1:] + x[:-1, :-1]) /2.0 permafrost_mask = draw_regions.get_permafrost_mask(lons2d, lats2d) mask_cond = (permafrost_mask <= 0) | (permafrost_mask >= 3) #plot_utils.apply_plot_params(width_pt=None, width_cm=25,height_cm=35, font_size=12) fig = plt.figure() assert isinstance(fig, Figure) h_max = 10 cmap = my_colormaps.get_lighter_jet_cmap(ncolors=10) #cm.get_cmap("jet",10) bounds = [0,0.1,0.5,1,2,3,5,8,9,10,11] norm = BoundaryNorm(boundaries=bounds,ncolors=len(bounds), clip=True) cmap.set_over(cmap(1.0)) clevels = np.arange(0,h_max+1,1) gs = gridspec.GridSpec(1,1) all_axes = [] all_img = [] print(basemap(-96.999, 68.42)) print(basemap(-2.4e7,6.3e6, inverse = True)) ax = fig.add_subplot(gs[0,0]) hm2d = np.ma.masked_where(mask_cond, hm2d) img = basemap.pcolormesh(x, y, hm2d, cmap = cmap, vmax = h_max, norm=norm) #img = basemap.contourf(x, y, hm2d, levels = clevels, cmap = cmap) ax.set_title("Mean ALT") all_axes.append(ax) all_img.append(img) print(("hm2d(min,max) = ",hm2d.min(), hm2d.max())) # ax = fig.add_subplot(gs[1,0]) # hc = np.ma.masked_where(hc < 0, hc) # hc = np.ma.masked_where(mask_cond | (hc > h_max) | hm2d.mask, hc) # img = basemap.contourf(x, y, hc, levels = clevels) # all_img.append(img) # all_axes.append(ax) # ax.set_title("ALT from climatology") # print("hc(min,max) = ",hc.min(), hc.max()) # ax = fig.add_subplot(gs[2,0]) # delta = hm2d - hc # delta = np.ma.masked_where(hc.mask | hm2d.mask, delta) # img = basemap.contourf(x, y, delta, levels = np.arange(-1,1.2,0.2),ax = ax, # cmap = my_colormaps.get_red_blue_colormap()) # all_img.append(img) # all_axes.append(ax) # ax.set_title("Mean - Derived from climatology") #print(np.where((hm2d < hc) & ~(hc.mask | hm2d.mask))) #zones = get_zone_polygons(path = "data/permafrost/permaice.shp", basemap=basemap) permafrost_mask = np.ma.masked_where((permafrost_mask < 0)|(permafrost_mask >= 4), permafrost_mask) for the_ax, the_img in zip( all_axes, all_img ): assert isinstance(the_ax, Axes) basemap.drawcoastlines(ax = the_ax, linewidth=0.5) divider = make_axes_locatable(the_ax) cax = divider.append_axes("right", "5%", pad="3%") cb = fig.colorbar(the_img, cax = cax, extend = "max", ticks = bounds) #CS = basemap.contour(x,y, permafrost_mask, levels = [1,2], # ax = the_ax, colors = "k", linewidth= 5) #the_ax.clabel(CS,colors = 'k', fmt="%d" , fontsize=8) basemap.readshapefile("data/pf_4/permafrost8_wgs84/permaice", name="zone", ax=the_ax, linewidth=1.5) #for p in zones: # the_ax.add_patch(p) fig.tight_layout() #cax_to_hide.set_visible(False) fig.savefig("alt_b1.png") plt.show() do_stats = False if not do_stats: return
def plot_precip(data_path = "/home/huziy/skynet1_rech3/crcm4_data"): seasons = ["(a) Annual", " (b) Winter (DJF)", "(c) Spring (MAM)", "(d) Summer (JJA)", "(e) Fall (SON)"] months = [range(1, 13), [12, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11] ] season_to_months = dict(zip(seasons, months)) #remove annual seasons.pop(0) #put new numbering for the subplots new_numbering = ["a", "b", "c", "d"] var_name = "pcp" year_range_c = xrange(1970,2000) year_range_f = xrange(2041,2071) x, y = polar_stereographic.xs, polar_stereographic.ys i_array, j_array = _get_routing_indices() x_min, x_max, y_min, y_max = plot_utils.get_ranges(x[i_array, j_array], y[i_array, j_array]) plot_utils.apply_plot_params(width_pt= None, font_size=9, aspect_ratio=2.5) fig = plt.figure() assert isinstance(fig, Figure) basemap = polar_stereographic.basemap assert isinstance(basemap, Basemap) gs = gridspec.GridSpec(3,2, height_ratios=[1,1,1], width_ratios=[1,1]) #determine min an max for color scales min_val = np.inf max_val = -np.inf for season in seasons: current = _get_data(v_name=var_name, months = season_to_months[season], member_list=members.current_ids, year_range=year_range_c) future = _get_data(v_name=var_name, months = season_to_months[season], member_list=members.future_ids, year_range=year_range_f) current_m = np.mean(current, axis=0) future_m = np.mean(future, axis= 0) delta = future_m[i_array, j_array] - current_m[i_array, j_array] the_min = delta.min() the_max = delta.max() min_val = min(min_val, the_min) max_val = max(max_val, the_max) min_val = np.floor(min_val) max_val = np.ceil(max_val) color_map = my_cm.get_red_blue_colormap(ncolors = 10, reversed=False) #color_map = mpl.cm.get_cmap(name="jet_r", lut=10) clevels = xrange(-8, 9, 2) all_plot_axes = [] for i, season in enumerate(seasons): row, col = i // 2, i % 2 ax = fig.add_subplot(gs[row, col ]) all_plot_axes.append(ax) current = _get_data(data_folder=data_path, v_name=var_name, months = season_to_months[season], member_list=members.current_ids, year_range=year_range_c) future = _get_data(data_folder=data_path, v_name=var_name, months = season_to_months[season], member_list=members.future_ids, year_range=year_range_f) #t, p = stats.ttest_ind(current, future, axis=0) #significant = np.array(p <= 0.05) significant = calculate_significance_using_bootstrap(current, future) assert not np.all(~significant) assert not np.all(significant) current_m = np.mean(current, axis=0) future_m = np.mean(future, axis= 0) seconds_per_day = 24 * 60 * 60 delta = (future_m - current_m) * seconds_per_day delta = np.array(delta) assert isinstance(ax, Axes) #delta = maskoceans(polar_stereographic.lons, polar_stereographic.lats, delta) save = delta[i_array, j_array] delta = np.ma.masked_all(delta.shape) delta[i_array, j_array] = save d_min = np.floor( min_val * 10 ) / 10.0 d_max = np.ceil( max_val *10 ) / 10.0 if d_min > 0: color_map = my_cm.get_blue_colormap(ncolors=10) img = basemap.pcolormesh(x, y, delta, cmap = color_map, vmin = d_min, vmax = d_max) divider = make_axes_locatable(ax) cax = divider.append_axes("right", "8%", pad="3%") assert isinstance(cax, Axes) int_ticker = LinearLocator(numticks = color_map.N + 1) cb = fig.colorbar(img, cax = cax, ticks = int_ticker) cax.set_title("mm/d") where_significant = significant significant = np.ma.masked_all(significant.shape) significant[(~where_significant)] = 0 save = significant[i_array, j_array] significant = np.ma.masked_all(significant.shape) significant[i_array, j_array] = save basemap.pcolormesh( x, y, significant , cmap = mpl.cm.get_cmap(name = "gray", lut = 3), vmin = -1, vmax = 1, ax = ax) ax.set_title( season.replace( re.findall( "([a-z])", season)[0], new_numbering[i]) ) #plot djf swe change season = " (b) Winter (DJF)" ax = fig.add_subplot(gs[2, : ]) all_plot_axes.append(ax) var_name = "sno" current = _get_data(data_folder=data_path, v_name=var_name, months = season_to_months[season], member_list=members.current_ids, year_range=year_range_c) future = _get_data(data_folder=data_path, v_name=var_name, months = season_to_months[season], member_list=members.future_ids, year_range=year_range_f) #t, p = stats.ttest_ind(current, future, axis=0) #significant = np.array(p <= 0.05) significant = calculate_significance_using_bootstrap(current, future) assert not np.all(~significant) assert not np.all(significant) current_m = np.mean(current, axis=0) future_m = np.mean(future, axis= 0) delta = future_m - current_m delta = np.array(delta) assert isinstance(ax, Axes) #delta = maskoceans(polar_stereographic.lons, polar_stereographic.lats, delta) save = delta[i_array, j_array] delta = np.ma.masked_all(delta.shape) delta[i_array, j_array] = save d_min = np.floor( np.min(save) * 10 ) / 10.0 d_max = np.ceil( np.max(save) *10 ) / 10.0 if d_min >= 0: color_map = my_cm.get_blue_colormap(ncolors=10) bounds = plot_utils.get_boundaries_for_colobar(d_min, d_max, color_map.N, lambda x: np.round(x, decimals=0)) bn = BoundaryNorm(bounds, color_map.N) img = basemap.pcolormesh(x, y, delta, cmap = color_map, vmin = bounds[0], vmax = bounds[-1], norm = bn) divider = make_axes_locatable(ax) cax = divider.append_axes("right", "8%", pad="3%") assert isinstance(cax, Axes) int_ticker = LinearLocator(numticks = color_map.N + 1) cb = fig.colorbar(img, cax = cax, ticks = bounds) cax.set_title("mm") where_significant = significant significant = np.ma.masked_all(significant.shape) significant[(~where_significant)] = 0 save = significant[i_array, j_array] significant = np.ma.masked_all(significant.shape) significant[i_array, j_array] = save basemap.pcolormesh( x, y, significant , cmap = mpl.cm.get_cmap(name = "gray", lut = 3), vmin = -1, vmax = 1, ax = ax) ax.set_title( season.replace( re.findall( "([a-z])", season)[0], "e")) #finish swe djf for the_ax in all_plot_axes: the_ax.set_xlim(x_min, x_max) the_ax.set_ylim(y_min, y_max) basemap.drawcoastlines(ax = the_ax, linewidth = 0.1) plot_utils.draw_meridians_and_parallels(basemap, step_degrees=30.0, ax = the_ax) plot_basin_boundaries_from_shape(basemap, axes = the_ax, linewidth=0.4) #gs.update(wspace=0.5) #gs.tight_layout(fig) #fig.suptitle("Projected changes, total precip (mm/day), CRCM4") fig.tight_layout() fig.savefig("proj_change_{0}_ccc.png".format(var_name)) pass
def plot_swe(): seasons = ["(a) Annual", " (b) Winter (DJF)", "(c) Spring (MAM)", "(d) Summer (JJA)", "(e) Fall (SON)"] months = [range(1, 13), [12, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11] ] season_to_months = dict(zip(seasons, months)) var_name = "sno" year_range_c = xrange(1970,2000) year_range_f = xrange(2041,2071) x, y = polar_stereographic.xs, polar_stereographic.ys i_array, j_array = _get_routing_indices() x_min, x_max, y_min, y_max = plot_utils.get_ranges(x[i_array, j_array], y[i_array, j_array]) _generate_mask_of_domain_of_interest(i_array, j_array) if True: return plot_utils.apply_plot_params(width_pt= None, font_size=9, aspect_ratio=2.5) fig = plt.figure() assert isinstance(fig, Figure) basemap = polar_stereographic.basemap assert isinstance(basemap, Basemap) gs = gridspec.GridSpec(3,4, height_ratios=[1,1,1], width_ratios=[1,1,1,1]) #color_map = my_cm.get_ color_map = my_cm.get_red_blue_colormap(ncolors = 10, reversed=True) #color_map = mpl.cm.get_cmap(name="jet_r", lut=10) clevels = xrange(-8, 9, 2) all_plot_axes = [] for i, season in enumerate(seasons): if not i: ax = fig.add_subplot(gs[0,1:3]) else: row, col = (i - 1) // 2 + 1, (i - 1) % 2 ax = fig.add_subplot(gs[row, col * 2 : col * 2 + 2 ]) all_plot_axes.append(ax) current = _get_data(v_name=var_name, months = season_to_months[season], member_list=members.current_ids, year_range=year_range_c) future = _get_data(v_name=var_name, months = season_to_months[season], member_list=members.future_ids, year_range=year_range_f) t, p = stats.ttest_ind(current, future, axis=0) #TODO: change it back to p <= 0.05 wheen doing real sign test significant = np.array(p <= 1) assert not np.all(~significant) assert not np.all(significant) current_m = np.mean(current, axis=0) future_m = np.mean(future, axis= 0) delta = (future_m - current_m) delta = np.array(delta) assert isinstance(ax, Axes) #delta = maskoceans(polar_stereographic.lons, polar_stereographic.lats, delta) save = delta[i_array, j_array] delta = np.ma.masked_all(delta.shape) delta[i_array, j_array] = save d_min = np.floor( np.min(save) ) d_max = np.ceil( np.max(save) ) bounds = plot_utils.get_boundaries_for_colobar(d_min, d_max, color_map.N, lambda x: np.round(x, decimals=10)) print bounds bn = BoundaryNorm(bounds, color_map.N) d = np.max( np.abs([d_min, d_max]) ) print season, np.min(delta), np.max(delta) #delta = np.ma.masked_where(delta < 0, delta ) img = basemap.pcolormesh(x, y, delta, cmap = color_map, norm = bn, vmin = bounds[0], vmax = bounds[-1]) divider = make_axes_locatable(ax) cax = divider.append_axes("right", "8%", pad="3%") assert isinstance(cax, Axes) int_ticker = LinearLocator(numticks = color_map.N + 1) cb = fig.colorbar(img, cax = cax, ticks = bounds, boundaries = bounds) where_significant = significant significant = np.ma.masked_all(significant.shape) significant[(~where_significant)] = 0 save = significant[i_array, j_array] significant = np.ma.masked_all(significant.shape) significant[i_array, j_array] = save basemap.pcolormesh( x, y, significant , cmap = mpl.cm.get_cmap(name = "gray", lut = 3), vmin = -1, vmax = 1, ax = ax) ax.set_title(season) for the_ax in all_plot_axes: the_ax.set_xlim(x_min, x_max) the_ax.set_ylim(y_min, y_max) basemap.drawcoastlines(ax = the_ax, linewidth = 0.1) plot_utils.draw_meridians_and_parallels(basemap, step_degrees=30.0, ax = the_ax) plot_basin_boundaries_from_shape(basemap, axes = the_ax, linewidth=0.4) gs.update(wspace=0.5) #gs.tight_layout(fig) fig.suptitle("Projected changes, SWE, mm, CRCM4") fig.savefig("proj_change_{0}_ccc.png".format(var_name)) pass
def plot_mean_alt_from_jpp_results(): start_year = 1981 end_year = 2008 path = "data/alts_by_jpp/MonTS_NA_ERA40_ALT_{0}_{1}".format(start_year, end_year) rObj = RPN(path) altt = rObj.get_all_time_records_for_name(varname="FALT") alt = np.mean( np.array(list(altt.values())), axis = 0) rObj.close() sim_data_folder = "/home/huziy/skynet1_rech3/cordex/CORDEX_DIAG/era40_driven_b1" coord_file = os.path.join(sim_data_folder, "pmNorthAmerica_0.44deg_ERA40-Int_B1_200812_moyenne") basemap, lons2d, lats2d = draw_regions.get_basemap_and_coords(resolution="c", file_path = coord_file, llcrnrlat=40.0, llcrnrlon=-145, urcrnrlon=-20, urcrnrlat=74 ) assert isinstance(basemap, Basemap) lons2d[lons2d > 180] -= 360 x, y = basemap(lons2d, lats2d) permafrost_mask = draw_regions.get_permafrost_mask(lons2d, lats2d) mask_cond = (permafrost_mask <= 0) | (permafrost_mask >= 3) alt = np.ma.masked_where(mask_cond, alt) fig = plt.figure() assert isinstance(fig, Figure) h_max = 10 cmap = my_colormaps.get_lighter_jet_cmap(ncolors=10) #cm.get_cmap("jet",10) bounds = [0,0.1,0.5,1,2,3,5,8,9,10,11] norm = BoundaryNorm(boundaries=bounds,ncolors=len(bounds), clip=True) #norm = None cmap.set_over(cmap(1.0)) clevels = np.arange(0,h_max+1,1) gs = gridspec.GridSpec(3,1) ax = fig.add_subplot(gs[0,0]) assert isinstance(ax, Axes) hc = np.ma.masked_where(mask_cond | (np.min(list(altt.values()), axis = 0) < 0), alt) #hc = np.ma.masked_where( (hc < 0), hc) img = basemap.pcolormesh(x, y, hc, cmap = cmap, vmax = h_max, norm=norm) ax.set_title("ALT, JPP ({0} - {1}) \n".format(start_year, end_year)) basemap.drawcoastlines(ax = ax, linewidth=0.5) basemap.readshapefile("data/pf_4/permafrost8_wgs84/permaice", name="zone", ax=ax, linewidth=1.5) divider = make_axes_locatable(ax) cax = divider.append_axes("right", "5%", pad="3%") cb = fig.colorbar(img, cax = cax, extend = "max", ticks = bounds) cax.set_title("m \n") fig.tight_layout(w_pad=0.0) fig.savefig("alt_jpp_current.png")
def plot_temp(): seasons = ["(a) Annual", " (b) Winter (DJF)", "(c) Spring (MAM)", "(d) Summer (JJA)", "(e) Fall (SON)"] months = [range(1, 13), [12, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11] ] season_to_months = dict(zip(seasons, months)) #take out annual seasons.pop(0) #put new numbering for the subplots new_numbering = ["a", "b", "c", "d"] var_name = "st" year_range_c = xrange(1970,2000) year_range_f = xrange(2041,2071) x, y = polar_stereographic.xs, polar_stereographic.ys i_array, j_array = _get_routing_indices() x_min, x_max, y_min, y_max = plot_utils.get_ranges(x[i_array, j_array], y[i_array, j_array]) plot_utils.apply_plot_params(width_pt= None, font_size=9, aspect_ratio=2.5) fig = plt.figure() assert isinstance(fig, Figure) basemap = polar_stereographic.basemap assert isinstance(basemap, Basemap) gs = gridspec.GridSpec(3,2) #color_map = mpl.cm.get_cmap(name="jet", lut=10) clevels = xrange(-8, 9, 2) all_plot_axes = [] #determine min an max for color scales min_val = np.inf max_val = -np.inf for season in seasons: current = _get_data(v_name=var_name, months = season_to_months[season], member_list=members.current_ids, year_range=year_range_c) future = _get_data(v_name=var_name, months = season_to_months[season], member_list=members.future_ids, year_range=year_range_f) current_m = np.mean(current, axis=0) future_m = np.mean(future, axis= 0) delta = future_m[i_array, j_array] - current_m[i_array, j_array] the_min = delta.min() the_max = delta.max() min_val = min(min_val, the_min) max_val = max(max_val, the_max) min_val = np.floor(min_val) max_val = np.ceil(max_val) color_map = my_cm.get_red_blue_colormap(ncolors = 10, reversed=True) if min_val >= 0: color_map = my_cm.get_red_colormap(ncolors=10) for i, season in enumerate(seasons): row, col = i // 2, i % 2 ax = fig.add_subplot(gs[row, col ]) all_plot_axes.append(ax) current = _get_data(v_name=var_name, months = season_to_months[season], member_list=members.current_ids, year_range=year_range_c) future = _get_data(v_name=var_name, months = season_to_months[season], member_list=members.future_ids, year_range=year_range_f) # t, p = stats.ttest_ind(current, future, axis=0) # significant = np.array(p <= 0.05) significant = calculate_significance_using_bootstrap(current, future) assert not np.all(~significant) assert not np.all(significant) current_m = np.mean(current, axis=0) future_m = np.mean(future, axis= 0) delta = (future_m - current_m) assert isinstance(ax, Axes) #delta = maskoceans(polar_stereographic.lons, polar_stereographic.lats, delta) save = delta[i_array, j_array] delta = np.ma.masked_all(delta.shape) delta[i_array, j_array] = save d_min = np.floor( np.min(save) ) d_max = np.ceil( np.max(save) ) img = basemap.pcolormesh(x, y, delta, cmap = color_map, vmin = min_val, vmax = max_val) divider = make_axes_locatable(ax) cax = divider.append_axes("right", "8%", pad="3%") assert isinstance(cax, Axes) int_ticker = LinearLocator(numticks = color_map.N + 1) cb = fig.colorbar(img, cax = cax, ticks = int_ticker) cax.set_title("$^{\\circ}{\\rm C}$") where_significant = significant significant = np.ma.masked_all(significant.shape) significant[~where_significant] = 0 basemap.pcolormesh( x, y, significant , cmap = mpl.cm.get_cmap(name = "gray", lut = 3), vmin = -1, vmax = 1, ax = ax) ax.set_title( season.replace( re.findall( "([a-z])", season)[0], new_numbering[i]) ) for the_ax in all_plot_axes: the_ax.set_xlim(x_min, x_max) the_ax.set_ylim(y_min, y_max) basemap.drawcoastlines(ax = the_ax, linewidth = 0.1) plot_utils.draw_meridians_and_parallels(basemap, step_degrees=30.0, ax = the_ax) plot_basin_boundaries_from_shape(basemap, axes = the_ax, linewidth=0.4) #gs.update(wspace=0.5) fig.tight_layout() #fig.suptitle("Projected changes, T(2m), degrees, CRCM4") fig.savefig("proj_change_{0}_ccc.png".format(var_name))
existing axes, creates a divider for it and returns an instance of the AxesLocator class. The append_axes method of this AxesLocator can then be used to create a new axes on a given side ("top", "right", "bottom", or "left") of the original axes. This example uses Axes Divider to add colorbars next to axes. """ import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable from mpl_toolkits.axes_grid1.colorbar import colorbar fig, (ax1, ax2) = plt.subplots(1, 2) fig.subplots_adjust(wspace=0.5) im1 = ax1.imshow([[1, 2], [3, 4]]) ax1_divider = make_axes_locatable(ax1) # add an axes to the right of the main axes. cax1 = ax1_divider.append_axes("right", size="7%", pad="2%") cb1 = colorbar(im1, cax=cax1) im2 = ax2.imshow([[1, 2], [3, 4]]) ax2_divider = make_axes_locatable(ax2) # add an axes above the main axes. cax2 = ax2_divider.append_axes("top", size="7%", pad="2%") cb2 = colorbar(im2, cax=cax2, orientation="horizontal") # change tick position to top. Tick position defaults to bottom and overlaps # the image. cax2.xaxis.set_ticks_position("top") plt.show()
def animate(self, t): print("current frame: {0}".format(self.current_frame_index)) #clear axes #for ax in self.axesDict.values(): # ax.cla() #prepare figure and subplot for animation fig = plt.figure() self.figure = fig gs = gridspec.GridSpec(2,2, width_ratios=[1,1]) axesDict = {} for i, vName in enumerate(self.var_names): if vName == "STFL": axesDict[vName] = fig.add_subplot(gs[0,0:2]) elif vName == "TT": axesDict[vName] = fig.add_subplot(gs[1,0]) elif vName == "PR": axesDict[vName] = fig.add_subplot(gs[1,1]) axesDict["TT"].set_title("Temperature (${\\rm ^\circ C}$)") axesDict["PR"].set_title("Precip (mm/day)") axesDict["STFL"].set_title("{0}-{1:02d} ({2})".format(t.year, t.month, self.seasons[0 if t.month == 12 else (t.month // 3)])) assert isinstance(fig, Figure) basemap = self.basemap all_axes = [] ax_to_levels = {} imgs = [] #fig.suptitle() #fig.suptitle("({0} - {1})".format(start_year, end_year)) #plot Temp levels = [-40, -30, -20, -10, -5, 0,5, 10, 15, 20, 25, 30] cmap = cm.get_cmap("jet", len(levels) - 1) bn = BoundaryNorm(levels, cmap.N) ax = axesDict["TT"] assert isinstance(ax, Axes) tt = self.temperatureVar[self.year_index,self.month_index,:,:] img = basemap.contourf(self.x, self.y, tt, levels = levels, cmap = cmap, norm = bn, ax = ax) all_axes.append(ax) imgs.append(img) ax_to_levels[ax] = levels #plot precip ax = axesDict["PR"] levels = np.arange(0, 15, 1.5) cmap = cm.get_cmap("jet", len(levels) - 1) bn = BoundaryNorm(levels, cmap.N) convert_factor = 1000.0 * 24 * 60 * 60 #m/s to mm/day pr = self.precipVar[self.year_index,self.month_index,:,:] * convert_factor img = basemap.contourf(self.x, self.y, pr, levels = levels, cmap = cmap, norm = bn, ax = ax) all_axes.append(ax) imgs.append(img) ax_to_levels[ax] = levels #plot stfl ax = axesDict["STFL"] levels = [0,50,100,200,300,500,750,1000, 1500,2000,5000,10000,15000] cmap = cm.get_cmap("jet", len(levels) - 1) bn = BoundaryNorm(levels, cmap.N) stfl = self.streamflowVar[self.year_index,self.month_index,:,:] stfl = np.ma.masked_where(self.stfl_mask, stfl) img = basemap.contourf(self.x, self.y, stfl, levels = levels, cmap = cmap, norm = bn, ax = ax) all_axes.append(ax) imgs.append(img) ax_to_levels[ax] = levels sf = ScalarFormatter(useMathText=True) sf.set_powerlimits([-3,4]) #draw coast lines for the_ax, the_img in zip(all_axes, imgs): basemap.drawcoastlines(ax = the_ax) divider = make_axes_locatable(the_ax) cax = divider.append_axes("right", "5%", pad="3%") cb = plt.colorbar(the_img, cax = cax, ticks = ax_to_levels[the_ax]) if the_ax == axesDict["STFL"]: cb.ax.set_ylabel("Streamflow (${\\rm m^3/s}$)") #self.redraw_colorbars = False self.current_frame_index += 1 self.year_index = self.current_frame_index // 12 self.month_index = self.current_frame_index % 12
def _plot_ica_properties(pick, ica, inst, psds_mean, freqs, n_trials, epoch_var, plot_lowpass_edge, epochs_src, set_title_and_labels, plot_std, psd_ylabel, spectrum_std, topomap_args, image_args, fig, axes, kind): """Plot ICA properties (helper).""" from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable from scipy.stats import gaussian_kde topo_ax, image_ax, erp_ax, spec_ax, var_ax = axes # plotting # -------- # component topomap _plot_ica_topomap(ica, pick, show=False, axes=topo_ax, **topomap_args) # image and erp plot_epochs_image(epochs_src, picks=pick, axes=[image_ax, erp_ax], combine=None, colorbar=False, show=False, **image_args) # spectrum spec_ax.plot(freqs, psds_mean, color='k') if plot_std: spec_ax.fill_between(freqs, psds_mean - spectrum_std[0], psds_mean + spectrum_std[1], color='k', alpha=.2) if plot_lowpass_edge: spec_ax.axvline(inst.info['lowpass'], lw=2, linestyle='--', color='k', alpha=0.2) # epoch variance var_ax_divider = make_axes_locatable(var_ax) hist_ax = var_ax_divider.append_axes("right", size="33%", pad="2.5%") var_ax.scatter(range(len(epoch_var)), epoch_var, alpha=0.5, facecolor=[0, 0, 0], lw=0) var_ax.set_yticks([]) # histogram & histogram _, counts, _ = hist_ax.hist(epoch_var, orientation="horizontal", color="k", alpha=.5) # kde kde = gaussian_kde(epoch_var) ymin, ymax = hist_ax.get_ylim() x = np.linspace(ymin, ymax, 50) kde_ = kde(x) kde_ /= kde_.max() kde_ *= hist_ax.get_xlim()[-1] * .9 hist_ax.plot(kde_, x, color="k") hist_ax.set_ylim(ymin, ymax) # aesthetics # ---------- topo_ax.set_title(ica._ica_names[pick]) set_title_and_labels(image_ax, kind + ' image and ERP/ERF', [], kind) # erp set_title_and_labels(erp_ax, [], 'Time (s)', 'AU\n') erp_ax.spines["right"].set_color('k') erp_ax.set_xlim(epochs_src.times[[0, -1]]) # remove half of yticks if more than 5 yt = erp_ax.get_yticks() if len(yt) > 5: erp_ax.yaxis.set_ticks(yt[::2]) # remove xticks - erp plot shows xticks for both image and erp plot image_ax.xaxis.set_ticks([]) yt = image_ax.get_yticks() image_ax.yaxis.set_ticks(yt[1:]) image_ax.set_ylim([-0.5, n_trials + 0.5]) # spectrum set_title_and_labels(spec_ax, 'Spectrum', 'Frequency (Hz)', psd_ylabel) spec_ax.yaxis.labelpad = 0 spec_ax.set_xlim(freqs[[0, -1]]) ylim = spec_ax.get_ylim() air = np.diff(ylim)[0] * 0.1 spec_ax.set_ylim(ylim[0] - air, ylim[1] + air) image_ax.axhline(0, color='k', linewidth=.5) # epoch variance set_title_and_labels(var_ax, kind + ' variance', kind + ' (index)', 'Arbitrary Units (AU)') hist_ax.set_ylabel("") hist_ax.set_yticks([]) set_title_and_labels(hist_ax, None, None, None) return fig
extent = extent_lm, aspect = aspect) im_dft_ax.set_title('Recovered Input (dft)') imgs.append(im) im_nudft_ax = subplot(gs[1, 3]) im = im_nudft_ax.imshow(noise_cube_nudft[0].reshape((nl, nm)), origin = 'lower', extent = extent_lm, aspect = aspect) im_nudft_ax.set_title('Recovered Input (nudft)') imgs.append(im) for i in np.arange(1, 5): a = fig.axes[i] if i < 3: a.set_xlabel('u', size=16) a.set_ylabel('v', size=16, rotation=0) else: a.set_xlabel('l', size=16) a.set_ylabel('m', size=16, rotation=0) for i,axe in enumerate(fig.axes): divider = make_axes_locatable(axe) cax = divider.append_axes("right", size="5%", pad=0.05) colorbar(imgs[i], cax=cax) gs.tight_layout(fig) show()