def generic_colorbar(low, high, label='', cmap=None, ax=None, ticks=None, **kwargs): extra_kwargs = { 'orientation': 'horizontal', 'label': label, 'ticks': ticks if ticks is not None else [low, high], } delta = (high - low) low = low - delta / 6 high = high + delta / 6 extra_kwargs.update(kwargs) cb = colorbar.ColorbarBase(ax, cmap=cm.get_cmap(cmap or 'Blues'), norm=colors.Normalize(vmin=low, vmax=high), **extra_kwargs) return cb
def plot_discretized_belief_halfcircle(belief_rewards, center_points, env, observations): fig = plt.figure() env.plot_behavior(observations, plot_env=True, color=cols_deep[3], linewidth=5) res = center_points[1, 0] - center_points[0, 0] normal = pl.Normalize(0., 1.) colors = pl.cm.gray(normal(belief_rewards)) for (x, y), c in zip(center_points, colors): rec = Rectangle((x, y), res, res, facecolor=c, alpha=0.85, edgecolor='none') plt.gca().add_patch(rec) cax, _ = cbar.make_axes(plt.gca()) cb2 = cbar.ColorbarBase(cax, cmap=pl.cm.gray, norm=normal) return fig
def saveDamagePlot(self, folderPath, dataName, channelName, nLevels): import pylab as plt from matplotlib.colors import LogNorm import matplotlib.colorbar as colorbar import matplotlib.cm as cm maxDamage = self.damage.max() levels = np.logspace(np.log10(maxDamage / 100.), np.log10(maxDamage), nLevels ) norm = LogNorm(vmin = maxDamage / 100., vmax = maxDamage) cmap = cm.get_cmap('jet', nLevels) fig = plt.figure() axes = fig.add_subplot(111) axes.contourf(self.damage, extent = (0, 180, 0, 180), norm = norm, cmap = cmap, levels = levels) #axes.contourf(self.damage) cbax, _ = colorbar.make_axes(axes) cb = colorbar.ColorbarBase(cbax, cmap=cmap, norm = norm) cb.set_label('Damage [-]') axes.set_xlabel(r'$\theta$ [deg]') axes.set_ylabel(r'$\varphi$ [deg]') axes.set_title('Damage for {}, channel {}'.format(dataName, channelName)) fig.savefig(os.path.join(folderPath, '{}_{}.png'.format(dataName, channelName)))
def make_colorbar(clevs, norm, cmap): """ Manual Color Bar """ ax = plt.axes([0.02, 0.1, 0.05, 0.8], frameon=False, yticks=[], xticks=[]) under = clevs[0]-(clevs[1]-clevs[0]) over = clevs[-1]+(clevs[-1]-clevs[-2]) blevels = np.concatenate([[under, ], clevs, [over, ]]) cb2 = mpcolorbar.ColorbarBase(ax, cmap=cmap, norm=norm, boundaries=blevels, extend='both', ticks=None, spacing='uniform', orientation='vertical') for i, lev in enumerate(clevs): y = float(i) / (len(clevs) - 1) fmt = '%g' txt = cb2.ax.text(0.5, y, fmt % (lev,), va='center', ha='center') txt.set_path_effects([PathEffects.withStroke(linewidth=2, foreground="w")]) ax.yaxis.set_ticklabels([])
def plot_regions_interest(self, ax=None): if ax is None: __, ax = plt.subplots() interests = self.compute_all_interests() interest_lims = (min(interests), max(interests)) normal = pylab.Normalize(*interest_lims) colors = pylab.cm.YlOrRd(normal(interests)) for region, color in zip(self.regions, colors): lengths = region.max_border - region.min_border ax.add_patch( patches.Rectangle(region.min_border, *lengths, fill=True, edgecolor='k', facecolor=color)) cax, _ = cbar.make_axes(ax) print("the interest lims are: ", interest_lims) cb2 = cbar.ColorbarBase(cax, cmap=pylab.cm.YlOrRd, norm=normal) ax.set_xlim(self.state_bounds[0][0], self.state_bounds[1][0]) ax.set_ylim(self.state_bounds[0][1], self.state_bounds[1][1])
def make_graph(cmatrix, timesteps, Numpoints, dt): """Create graphs of the model results using matplotlib. """ # Create a figure with size 15, 5 fig, ax = plt.subplots(1, 1, figsize=(15, 5)) # Set the figure title, and the axes labels. fig.text( 0.25, 0.95, "Concentrations Results from t = %.3fs to %.3fs" % (0, dt * timesteps), ) ax.set_ylabel("Concentration") ax.set_xlabel("Grid Point") # We use color to differentiate lines at different times. Set up the color map cmap = plt.get_cmap("nipy_spectral") cNorm = colors.Normalize(vmin=0, vmax=1.0 * timesteps) cNorm_inseconds = colors.Normalize(vmin=0, vmax=1.0 * timesteps * dt) scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cmap) # Only try to plot 20 lines, so choose an interval if more than that (i.e. plot # every interval lines interval = np.int(np.ceil(timesteps / 20)) # Do the main plot for time in range(0, timesteps, interval): colorVal = scalarMap.to_rgba(time) ax.plot(cmatrix[time, :], color=colorVal) # Add the custom colorbar ax2 = fig.add_axes([0.95, 0.05, 0.05, 0.9]) cb1 = colorbar.ColorbarBase(ax2, cmap=cmap, norm=cNorm_inseconds) cb1.set_label("Time (s)") return
def plot_sampling_dists_2D( self, opt_x=True, figsize=(12,10), samples=None, perc=100, plot_peak_lines=True, only_post_idx=None, params=None, post_colors=None, max_2d=False, max_1d=False ): if self.prior_marginal_2d is None: self.compute_values(only_1d=False) # Maxima for plotting. if max_1d is True: max_1d = self.marginal_1d_max else: max_1d = None if max_2d is True: max_2d = self.marginal_2d_max else: max_2d = None if params is None: params = self.params.p_names else: params = [param for param in self.params.p_names if param in params] if opt_x: x = self.opt_x else: x = self.sim_x if post_colors is None: post_colors = [(i, 0, 0) for i in np.linspace(0.3,1,len(self.posterior_list))] # Plot marginals. 1d and 2d. fig = plt.figure(figsize=figsize) for col_idx, col_param in enumerate(params): for row_idx, row_param in enumerate(params): ax = plt.subplot2grid((len(params), len(params)), (row_idx, col_idx)) # Get bounds. x_bounds = [x[col_param][np.isfinite(x[col_param])][0], x[col_param][np.isfinite(x[col_param])][-1]] if not opt_x: x_bounds = [float("{0:.3f}".format(x_bounds[0])), float("{0:.3f}".format(np.nanpercentile(x[col_param], perc)))] y_bounds = [x[row_param][np.isfinite(x[row_param])][0], x[row_param][np.isfinite(x[row_param])][-1]] if not opt_x: y_bounds = y_bounds = [float("{0:.3f}".format(y_bounds[0])), float("{0:.3f}".format(np.nanpercentile(x[row_param], perc)))] # Set x-ticks. ax.set_xlim(x_bounds) if row_idx+1 == len(params): ax.set_xticks(x_bounds) ax.tick_params(axis='x', rotation=90) else: ax.set_xticks([]) # Plot 1d marginals if col_idx == row_idx: ax.set_yticks([]) for post_idx, post_marginal_1d in enumerate(self.post_marginal_1d_list): ax.plot(x[col_param], post_marginal_1d[col_param], label = 'post marginals', c=post_colors[post_idx]) ax.plot(x[col_param], self.prior_marginal_1d[col_param], label='prior', c='k') if plot_peak_lines: plt.axvline(x[col_param][np.argmax(self.prior_marginal_1d[col_param])], c='k', alpha=0.5) for post_idx, post_marginal_1d in enumerate(self.post_marginal_1d_list): plt.axvline(x[col_param][np.argmax(post_marginal_1d[col_param])], c=post_colors[post_idx], alpha=0.5) ax.set_ylim([0, max_1d]) ax2 = ax.twinx() ax2.set_yticks([]) if samples is not None: if samples[col_param].size < 10: for sample in samples[col_param]: if not opt_x: ax2.axvline(sample, c='k', linestyle='--', alpha=.5) else: ax2.axvline(self.params.sim_param2opt_param(sample, name=col_param), c='k', linestyle='--', alpha=.5) else: if not opt_x: ax2.hist(samples[col_param], facecolor='k', alpha=.3, range=x_bounds, align='mid', bins=41) else: ax2.hist(self.params.sim_param2opt_param(samples[col_param], name=col_param), facecolor='k', alpha=.3, range=x_bounds, align='mid', bins=41) else: # Set y-ticks. ax.set_ylim(y_bounds) if col_idx == 0: ax.set_yticks(y_bounds) else: ax.set_yticks([]) # Plot 2d post marginals if col_idx > row_idx: if samples is not None: if 'params' in samples: samples_x = samples['params'][col_param].copy() samples_y = samples['params'][row_param].copy() elif col_param in samples and row_param in samples: samples_x = samples[col_param].copy() samples_y = samples[row_param].copy() if opt_x: samples_x = self.params.sim_param2opt_param(samples_x, name=col_param) samples_y = self.params.sim_param2opt_param(samples_y, name=row_param) plt.scatter(samples_x, samples_y, marker='*', zorder=100, edgecolor='b', facecolor=None, s=1) if len(self.posterior_list) > 1 and only_post_idx is None: for post_idx, post_mu in enumerate(self.post_mu_list): plt.plot(post_mu[col_idx], post_mu[row_idx], marker='.', c=post_colors[post_idx]) else: if len(self.posterior_list) == 1: post_idx = 0 else: post_idx = only_post_idx # Get x and y. xx = self.post_marginal_2d_list[post_idx][col_param][row_param][0] yy = self.post_marginal_2d_list[post_idx][col_param][row_param][1] if not opt_x: xx = self.params.opt_param2sim_param(xx, col_param) yy = self.params.opt_param2sim_param(yy, row_param) # Plot contour lines of post. zz = self.post_marginal_2d_list[post_idx][col_param][row_param][2] plt.contour(xx, yy, zz, cmap=cm.gist_heat_r, vmin=0, vmax=max_2d, origin='lower') if plot_peak_lines: plt.axvline(x[col_param][np.argmax(self.post_marginal_1d_list[post_idx][col_param])], c='r', alpha=0.5) plt.axhline(x[row_param][np.argmax(self.post_marginal_1d_list[post_idx][row_param])], c='r', alpha=0.5) # Plot 2d prior marginals elif col_idx < row_idx: # Get x and y. xx = self.prior_marginal_2d[col_param][row_param][0] yy = self.prior_marginal_2d[col_param][row_param][1] if not opt_x: xx = self.params.opt_param2sim_param(xx, col_param) yy = self.params.opt_param2sim_param(yy, row_param) # Plot contour lines of prior. zz = self.prior_marginal_2d[col_param][row_param][2] plt.contour(xx, yy, zz, cmap=cm.Greys, vmin=0, vmax=max_2d, origin='lower') if plot_peak_lines: plt.axvline(x[col_param][np.argmax(self.prior_marginal_1d[col_param])], c='k', alpha=0.5) plt.axhline(x[row_param][np.argmax(self.prior_marginal_1d[row_param])], c='k', alpha=0.5) if row_idx == 0: ax.set_title(col_param, fontsize=12, rotation=90, verticalalignment='bottom') if col_idx == 0: ax.set_ylabel(row_param, fontsize=12, rotation=0, horizontalalignment='right') #plt.tight_layout() ax = fig.add_axes((1, 0.6, 0.01, 0.3)) cb = colorbar.ColorbarBase(ax, cmap=cm.gist_heat_r, norm=colors.Normalize(vmin=0, vmax=max_2d), orientation='vertical') cb.set_label('p_post') ax = fig.add_axes((1, 0.15, 0.01, 0.3)) cb = colorbar.ColorbarBase(ax, cmap=cm.Greys, norm=colors.Normalize(vmin=0, vmax=max_2d), orientation='vertical') cb.set_label('p_prior') plt.show()
def rand_cmap(nlabels, type='bright', first_color_black=True, last_color_black=False, verbose=True): """ Creates a random colormap to be used together with matplotlib. Useful for segmentation tasks :param nlabels: Number of labels (size of colormap) :param type: 'bright' for strong colors, 'soft' for pastel colors :param first_color_black: Option to use first color as black, True or False :param last_color_black: Option to use last color as black, True or False :param verbose: Prints the number of labels and shows the colormap. True or False :return: colormap for matplotlib """ from matplotlib.colors import LinearSegmentedColormap import colorsys import numpy as np if type not in ('bright', 'soft'): print ('Please choose "bright" or "soft" for type') return if verbose: print('Number of labels: ' + str(nlabels)) # Generate color map for bright colors, based on hsv if type == 'bright': randHSVcolors = [(np.random.uniform(low=0.0, high=1), np.random.uniform(low=0.2, high=1), np.random.uniform(low=0.9, high=1)) for i in range(nlabels)] # Convert HSV list to RGB randRGBcolors = [] for HSVcolor in randHSVcolors: randRGBcolors.append(colorsys.hsv_to_rgb(HSVcolor[0], HSVcolor[1], HSVcolor[2])) if first_color_black: randRGBcolors[0] = [0, 0, 0] if last_color_black: randRGBcolors[-1] = [0, 0, 0] random_colormap = LinearSegmentedColormap.from_list('new_map', randRGBcolors, N=nlabels) return randRGBcolors # Generate soft pastel colors, by limiting the RGB spectrum if type == 'soft': low = 0.6 high = 0.95 randRGBcolors = [(np.random.uniform(low=low, high=high), np.random.uniform(low=low, high=high), np.random.uniform(low=low, high=high)) for i in range(nlabels)] if first_color_black: randRGBcolors[0] = [0, 0, 0] if last_color_black: randRGBcolors[-1] = [0, 0, 0] random_colormap = LinearSegmentedColormap.from_list('new_map', randRGBcolors, N=nlabels) return randRGBcolors # Display colorbar if verbose: from matplotlib import colors, colorbar from matplotlib import pyplot as plt fig, ax = plt.subplots(1, 1, figsize=(15, 0.5)) bounds = np.linspace(0, nlabels, nlabels + 1) norm = colors.BoundaryNorm(bounds, nlabels) cb = colorbar.ColorbarBase(ax, cmap=random_colormap, norm=norm, spacing='proportional', ticks=None, boundaries=bounds, format='%1i', orientation=u'horizontal') return random_colormap
pop_inc = pop_data.get(kommune_id).inc color = cm.coolwarm(inc_normalize(pop_inc)) if not isnan(pop_inc) else 'k' kommune_land = LANDMASS.intersection(sg.Polygon(kommune_loop)) # The kommune is inland if type(kommune_land) == sg.polygon.Polygon: x, y = kommune_land.exterior.xy ax.fill(x, y, alpha=0.5, fc=color) # The kommune is split by sea elif type(kommune_land) == sg.multipolygon.MultiPolygon: for kommune_land_part in kommune_land: x, y = kommune_land_part.exterior.xy ax.fill(x, y, alpha=0.5, fc=color) # The kommune is in the sea elif type(kommune_land) == sg.collection.GeometryCollection: print("Error, no intersection") cax, _ = cbar.make_axes(ax, location='right') cb = cbar.ColorbarBase(cax, cmap=cm.coolwarm, norm=inc_normalize, orientation='vertical', format='%.0f%%', label="Økning") f.show() f.savefig("Befolkningsvekst.png")
# get zorder for plotting sortidx = argsort(argsort(array(evml))) for i, ed in enumerate(evdp): #if ed != 10.: #get colour idx colidx = int(ed - zmin) if colidx > 9: colidx = 9 if colidx < 0: colidx == 0 color = cs[colidx] p = plt.bar(evdt[i], evml[i], width=width, color=color, edgecolor=color, zorder=300-sortidx[i]+20) plt.grid(True, which='major',axis='both') # get xlim plt.xlim([datetime(2012,6,18), datetime(2012,8,1)]) plt.xlabel('Earthquake Date', fontsize=14) plt.ylabel('Local Magnitude', fontsize=14) plt.ylim([0, 6]) cmap2 = cmap.from_list('custom', cs, N=ncols) #, ncols #norm = mpl.colors.BoundaryNorm(ticks, cmap.N) cax = fig.add_axes([0.91,0.15,0.015,0.7]) # setup colorbar axes. norm = mpl.colors.Normalize(vmin=zmin, vmax=zmax) cb = colorbar.ColorbarBase(cax, cmap=cmap2, orientation='vertical', norm=norm) # norm=norm cb.set_label('Earthquake Depth (km)') plt.savefig('moe_time_dep_zoom.png', format='png', bbox_inches='tight', dpi=300) plt.show()
def slice2(slcfname,starfname,fields_to_draw,zoom=1.,aux={},\ writefile=True,tstamp=True,stars=True,field_label=True,norm_factor=2): plt.rc('font', size=14) plt.rc('xtick', labelsize=14) plt.rc('ytick', labelsize=14) slc_data = pickle.load(open(slcfname, 'rb')) x0 = slc_data['yextent'][0] y0 = slc_data['yextent'][3] Lx = slc_data['yextent'][1] - slc_data['yextent'][0] Lz = slc_data['yextent'][3] - slc_data['yextent'][2] Lz = Lz / zoom ix = 2 iz = ix * Lz / Lx nf = len(fields_to_draw) fig = plt.figure(1, figsize=(ix * nf, iz + ix * 1.2)) gs = gridspec.GridSpec(2, nf, height_ratios=[iz, ix]) gs.update(top=0.95, left=0.10, right=0.95, wspace=0.05, hspace=0) if stars: sp = read_starvtk(starfname) if 'time' in slc_data: tMyr = slc_data['time'] else: time, sp = read_starvtk(starfname, time_out=True) tMyr = time * Myr images = [] for i, axis in enumerate(['y', 'z']): for j, f in enumerate(fields_to_draw): ax = plt.subplot(gs[i, j]) if f is 'star_particles': scatter_sp(sp, ax, axis=axis, norm_factor=norm_factor, type='surf') if axis is 'y': ax.set_xlim(x0, x0 + Lx) ax.set_ylim(y0, y0 + Lz) if axis is 'z': ax.set_xlim(x0, x0 + Lx) ax.set_ylim(x0, x0 + Lx) ax.set_aspect(1.0) else: data = slc_data[axis][f] im = ax.imshow(data, origin='lower', interpolation='bilinear') if f in aux: if 'norm' in aux[f]: im.set_norm(aux[f]['norm']) if 'cmap' in aux[f]: im.set_cmap(aux[f]['cmap']) if 'clim' in aux[f]: im.set_clim(aux[f]['clim']) extent = slc_data[axis + 'extent'] im.set_extent(extent) images.append(im) ax.set_xlim(extent[0], extent[1]) ax.set_ylim(extent[2], extent[3]) for j, (im, f) in enumerate(zip(images, fields_to_draw[1:])): ax = plt.subplot(gs[0, j + 1]) divider = make_axes_locatable(ax) cax = divider.append_axes("top", "3%", pad="1%") cbar = fig.colorbar(im, cax=cax, orientation='horizontal') if f in aux: if 'label' in aux[f]: cbar.set_label(aux[f]['label']) if 'cticks' in aux[f]: cbar.set_ticks(aux[f]['cticks']) cax.xaxis.tick_top() cax.xaxis.set_label_position('top') ax = plt.subplot(gs[0, 0]) divider = make_axes_locatable(ax) cax = divider.append_axes("top", "3%", pad="1%") cbar = colorbar.ColorbarBase(cax, ticks=[0, 20, 40], cmap=plt.cm.cool_r, norm=Normalize(vmin=0, vmax=40), orientation='horizontal') cax.xaxis.tick_top() cax.xaxis.set_label_position('top') cbar.set_label(r'${\rm age [Myr]}$') s1 = ax.scatter(Lx * 2, Lz * 2, s=np.sqrt(1.e3) / norm_factor, color='k', alpha=.8, label=r'$10^3 M_\odot$') s2 = ax.scatter(Lx * 2, Lz * 2, s=np.sqrt(1.e4) / norm_factor, color='k', alpha=.8, label=r'$10^4 M_\odot$') s3 = ax.scatter(Lx * 2, Lz * 2, s=np.sqrt(1.e5) / norm_factor, color='k', alpha=.8, label=r'$10^5 M_\odot$') ax.set_xlim(x0, x0 + Lx) ax.set_ylim(y0, y0 + Lz) legend = ax.legend( (s1, s2, s3), (r'$10^3 M_\odot$', r'$10^4 M_\odot$', r'$10^5 M_\odot$'), scatterpoints=1, loc='lower left', fontsize='medium', frameon=True) axes = fig.axes plt.setp([ax.get_xticklabels() for ax in axes[:2 * nf]], visible=False) plt.setp([ax.get_yticklabels() for ax in axes[:2 * nf]], visible=False) plt.setp(axes[:nf], 'ylim', (slc_data['yextent'][2] / zoom, slc_data['yextent'][3] / zoom)) plt.setp(axes[nf:2 * nf], 'xlabel', 'x [kpc]') plt.setp(axes[0], 'ylabel', 'z [kpc]') if tstamp: ax = axes[0] ax.text(0.5, 0.95, 't=%3d Myr' % tMyr, size=16, horizontalalignment='center', transform=ax.transAxes, **(texteffect())) plt.setp(axes[nf], 'ylabel', 'y [kpc]') plt.setp([ax.get_xticklabels() for ax in axes[nf:]], visible=True) plt.setp([ax.get_yticklabels() for ax in axes[:2 * nf:nf]], visible=True) plt.setp([ax.xaxis.get_majorticklabels() for ax in axes[nf:2 * nf]], rotation=45) pngfname = slcfname + 'ng' #canvas = mpl.backends.backend_agg.FigureCanvasAgg(fig) #canvas.print_figure(pngfname,num=1,dpi=150,bbox_inches='tight') if writefile: plt.savefig(pngfname, bbox_inches='tight', num=1, dpi=150) plt.close(1) else: return fig
def plot_slice(slcfname,vtkfname,fields_to_draw,zoom=1.,\ writefile=True,tstamp=True,stars=True,field_label=True): global aux plt.rc('font', size=14) plt.rc('xtick', labelsize=14) plt.rc('ytick', labelsize=14) slc_data = pickle.load(open(slcfname, 'rb')) x0 = slc_data['yextent'][0] y0 = slc_data['yextent'][3] Lx = slc_data['yextent'][1] - slc_data['yextent'][0] Lz = slc_data['yextent'][3] - slc_data['yextent'][2] Nx, Nz = slc_data['y']['nH'].shape Lz = Lz / zoom ix = 2 iz = ix * Lz / Lx nf = len(fields_to_draw) fig = plt.figure(1, figsize=(ix * nf + ix, iz + ix * 2)) gs = gridspec.GridSpec(2, nf, height_ratios=[iz, ix]) gs.update(left=0.10, right=0.90, wspace=0, hspace=0) sp = read_starvtk(vtkfname[:-3] + 'starpar.vtk') if slc_data.has_key('time'): tMyr = slc_data['time'] else: time, sp = read_starvtk(vtkfname[:-3] + 'starpar.vtk', time_out=True) tMyr = time * Myr images = [] for i, axis in enumerate(['y', 'z']): for j, f in enumerate(fields_to_draw): data = slc_data[axis][f] ax = plt.subplot(gs[i, j]) im = ax.imshow(data, origin='lower') if aux[f]['log']: im.set_norm(LogNorm()) extent = slc_data[axis + 'extent'] im.set_extent(extent) im.set_cmap(aux[f]['cmap']) im.set_clim(aux[f]['clim']) images.append(im) if stars: if j == 0: scatter_sp(sp, ax, axis=axis, runaway=False, norm_factor=4.) elif j == 1: scatter_sp(sp, ax, axis=axis, norm_factor=4.) ax.set_xlim(extent[0], extent[1]) ax.set_ylim(extent[2], extent[3]) gs2 = gridspec.GridSpec(nf + 2 + stars, 1) gs2.update(left=0.91, right=0.93, hspace=0.05) for j, (im, f) in enumerate(zip(images, fields_to_draw)): cax = plt.subplot(gs2[j + stars]) cbar = fig.colorbar(im, cax=cax, orientation='vertical') cbar.set_label(aux[f]['label']) #cax.xaxis.tick_top() #cax.xaxis.set_label_position('top') if aux[f].has_key('cticks'): cbar.set_ticks(aux[f]['cticks']) if stars: cax = plt.subplot(gs2[0]) cbar = colorbar.ColorbarBase(cax, ticks=[0, 20, 40], cmap=plt.cm.cool_r, norm=Normalize(vmin=0, vmax=40), orientation='vertical') cbar.set_label(r'${\rm age [Myr]}$') axes = fig.axes[:2 * nf] if field_label: for ax, f in zip(axes[:nf], fields_to_draw): lab = aux[f]['label'] label = lab[:lab.rfind(r'\;')] + '$' ax.text(0.5, 0.95, label, size=20, horizontalalignment='center', transform=ax.transAxes, **(texteffect())) if stars: legend = sp_legend(axes[-1], top=False, norm_factor=4.) plt.setp([ax.get_xticklabels() for ax in axes[:2 * nf]], visible=False) plt.setp([ax.get_yticklabels() for ax in axes[:2 * nf]], visible=False) plt.setp(axes[:nf], 'ylim', (slc_data['yextent'][2] / zoom, slc_data['yextent'][3] / zoom)) plt.setp(axes[nf:2 * nf], 'xlabel', 'x [kpc]') plt.setp(axes[0], 'ylabel', 'z [kpc]') if tstamp: # axes[0].text(x0*0.9,y0*0.9, # 't=%3d Myr' % tMyr,ha='left',va='top',**(texteffect(16))) plt.setp(axes[0], 'title', 't=%3d Myr' % tMyr) plt.setp(axes[nf], 'ylabel', 'y [kpc]') plt.setp([ax.get_xticklabels() for ax in axes[nf:]], visible=True) plt.setp([ax.get_yticklabels() for ax in axes[:2 * nf:nf]], visible=True) plt.setp([ax.xaxis.get_majorticklabels() for ax in axes[nf:2 * nf]], rotation=45) pngfname = slcfname[:-1] + 'png' #canvas = mpl.backends.backend_agg.FigureCanvasAgg(fig) #canvas.print_figure(pngfname,num=1,dpi=150,bbox_inches='tight') if writefile: plt.savefig(pngfname, bbox_inches='tight', num=1, dpi=150) plt.close()
def plot_results(self): self.plotted_beam = None if super().plot_results(): if self.spectro_plot_canvas is None: self.spectro_plot_canvas = PlotWindow.PlotWindow( roi=False, control=False, position=False, plugins=False, logx=False, logy=False) self.spectro_plot_canvas.setDefaultPlotLines(False) self.spectro_plot_canvas.setDefaultPlotPoints(True) self.spectro_plot_canvas.setZoomModeEnabled(True) self.spectro_plot_canvas.setMinimumWidth(673) self.spectro_plot_canvas.setMaximumWidth(673) pos = self.spectro_plot_canvas._plot.graph.ax.get_position() self.spectro_plot_canvas._plot.graph.ax.set_position( [pos.x0, pos.y0, pos.width * 0.86, pos.height]) pos = self.spectro_plot_canvas._plot.graph.ax2.get_position() self.spectro_plot_canvas._plot.graph.ax2.set_position( [pos.x0, pos.y0, pos.width * 0.86, pos.height]) ax3 = self.spectro_plot_canvas._plot.graph.fig.add_axes( [.82, .15, .05, .75]) self.spectro_image_box.layout().addWidget( self.spectro_plot_canvas) else: self.spectro_plot_canvas.clear() self.spectro_plot_canvas.setDefaultPlotLines(False) self.spectro_plot_canvas.setDefaultPlotPoints(True) ax3 = self.spectro_plot_canvas._plot.graph.fig.axes[-1] ax3.cla() number_of_bins = self.spectro_number_of_bins + 1 x, y, auto_x_title, auto_y_title, xum, yum = self.get_titles() if self.plotted_beam is None: self.plotted_beam = self.input_beam xrange, yrange = self.get_ranges(self.plotted_beam._beam, x, y) min_k = numpy.min(self.plotted_beam._beam.rays[:, 10]) max_k = numpy.max(self.plotted_beam._beam.rays[:, 10]) if self.spectro_variable == 0: #Energy energy_min = ShadowPhysics.getEnergyFromShadowK(min_k) energy_max = ShadowPhysics.getEnergyFromShadowK(max_k) bins = energy_min + numpy.arange(0, number_of_bins + 1) * ( (energy_max - energy_min) / number_of_bins) normalization = colors.Normalize(vmin=energy_min, vmax=energy_max) else: #wavelength wavelength_min = ShadowPhysics.getWavelengthfromShadowK(max_k) wavelength_max = ShadowPhysics.getWavelengthfromShadowK(min_k) bins = wavelength_min + numpy.arange(0, number_of_bins + 1) * ( (wavelength_max - wavelength_min) / number_of_bins) normalization = colors.Normalize(vmin=wavelength_min, vmax=wavelength_max) scalarMap = cmx.ScalarMappable(norm=normalization, cmap=self.color_map) cb1 = colorbar.ColorbarBase(ax3, cmap=self.color_map, norm=normalization, orientation='vertical') if self.spectro_variable == 0: #Energy cb1.set_label('Energy [eV]') else: cb1.set_label('Wavelength [Å]') go = numpy.where(self.plotted_beam._beam.rays[:, 9] == 1) lo = numpy.where(self.plotted_beam._beam.rays[:, 9] != 1) rays_to_plot = self.plotted_beam._beam.rays if self.rays == 1: rays_to_plot = self.plotted_beam._beam.rays[go] elif self.rays == 2: rays_to_plot = self.plotted_beam._beam.rays[lo] factor_x = ShadowPlot.get_factor(x, self.workspace_units_to_cm) factor_y = ShadowPlot.get_factor(y, self.workspace_units_to_cm) for index in range(0, number_of_bins): min_value = bins[index] max_value = bins[index + 1] if index < number_of_bins - 1: if self.spectro_variable == 0: #Energy cursor = numpy.where((numpy.round( ShadowPhysics.getEnergyFromShadowK( rays_to_plot[:, 10]), 4) >= numpy.round(min_value, 4)) & (numpy.round( ShadowPhysics.getEnergyFromShadowK( rays_to_plot[:, 10]), 4) < numpy.round( max_value, 4))) else: cursor = numpy.where((numpy.round( ShadowPhysics.getWavelengthfromShadowK( rays_to_plot[:, 10]), 4) >= numpy.round(min_value, 4)) & (numpy.round( ShadowPhysics.getWavelengthfromShadowK( rays_to_plot[:, 10]), 4) < numpy.round( max_value, 4))) else: if self.spectro_variable == 0: #Energy cursor = numpy.where((numpy.round( ShadowPhysics.getEnergyFromShadowK( rays_to_plot[:, 10]), 4) >= numpy.round(min_value, 4)) & (numpy.round( ShadowPhysics.getEnergyFromShadowK( rays_to_plot[:, 10]), 4) <= numpy.round( max_value, 4))) else: cursor = numpy.where((numpy.round( ShadowPhysics.getWavelengthfromShadowK( rays_to_plot[:, 10]), 4) >= numpy.round(min_value, 4)) & (numpy.round( ShadowPhysics.getWavelengthfromShadowK( rays_to_plot[:, 10]), 4) <= numpy.round( max_value, 4))) color = scalarMap.to_rgba((bins[index] + bins[index + 1]) / 2) if index == 0: self.spectro_plot_canvas.setActiveCurveColor(color=color) self.replace_spectro_fig(rays_to_plot[cursor], x, y, factor_x, factor_y, title=self.title + str(index), color=color) self.spectro_plot_canvas.setGraphXLimits(xrange[0] * factor_x, xrange[1] * factor_x) self.spectro_plot_canvas.setGraphYLimits(yrange[0] * factor_y, yrange[1] * factor_y) self.spectro_plot_canvas.setGraphXLabel(auto_x_title) self.spectro_plot_canvas.setGraphYLabel(auto_y_title) self.spectro_plot_canvas.replot()
def plot(self): """ plot residual phase tensor """ #get residual phase tensor for plotting self._compute_residual_pt() #filter data if desired if self.med_filt_kernel is not None: self._apply_median_filter(kernel=self.med_filt_kernel) #set position properties for the plot plt.rcParams['font.size'] = self.font_size plt.rcParams['figure.subplot.left'] = self.subplot_left plt.rcParams['figure.subplot.right'] = self.subplot_right plt.rcParams['figure.subplot.bottom'] = self.subplot_bottom plt.rcParams['figure.subplot.top'] = self.subplot_top plt.rcParams['figure.subplot.wspace'] = self.subplot_wspace plt.rcParams['figure.subplot.hspace'] = self.subplot_hspace #make figure instance self.fig = plt.figure(self.fig_num, self.fig_size, dpi=self.fig_dpi) #create axis instance, be sure to make aspect equal or ellipses will #look funny. self.ax = self.fig.add_subplot(1, 1, 1, aspect='equal') #set local parameters with shorter names es = self.ellipse_size ck = self.ellipse_colorby cmap = self.ellipse_cmap ckmin = float(self.ellipse_range[0]) ckmax = float(self.ellipse_range[1]) try: ckstep = float(self.ellipse_range[2]) except IndexError: ckstep = 3 #set the number of segments in case a segmented map is desired nseg = float((ckmax - ckmin) / (2 * ckstep)) if cmap == 'mt_seg_bl2wh2rd': bounds = np.arange(ckmin, ckmax + ckstep, ckstep) #get largest ellipse emax = self.ellipse_scale #emax = self.rpt_array['phimax'].max() #plot phase tensor ellipses for ii, rpt in enumerate(self.rpt_array): phimax = rpt['phimax'] phimin = rpt['phimin'] azimuth = rpt['azimuth'] #get the properties to color the ellipses by try: color_array = rpt[self.ellipse_colorby] except ValueError: raise NameError('{0} is not supported'.format( self.ellipse_colorby)) for jj, ff in enumerate(self.freq_list): if phimin[jj] == 0.0 or phimax[jj] == 0.0: pass else: #make sure the ellipses will be visable eheight = phimin[jj] / emax * es ewidth = phimax[jj] / emax * es #create an ellipse scaled by phimin and phimax and orient #the ellipse so that north is up and east is right #need to add 90 to do so instead of subtracting if self.rot90 == True: ellipd = patches.Ellipse( (rpt['offset'] * self.xstretch, np.log10(ff) * self.ystretch), width=ewidth, height=eheight, angle=azimuth[jj] - 90) else: ellipd = patches.Ellipse( (rpt['offset'] * self.xstretch, np.log10(ff) * self.ystretch), width=ewidth, height=eheight, angle=azimuth[jj]) #get ellipse color if cmap.find('seg') > 0: ellipd.set_facecolor( mtcl.get_plot_color(color_array[jj], self.ellipse_colorby, cmap, ckmin, ckmax, bounds=bounds)) else: ellipd.set_facecolor( mtcl.get_plot_color(color_array[jj], self.ellipse_colorby, cmap, ckmin, ckmax)) # == =add the ellipse to the plot == ======== self.ax.add_artist(ellipd) #--> Set plot parameters #need to sort the offsets and station labels so they plot correctly sdtype = [('offset', np.float), ('station', '|S10')] slist = np.array([(oo, ss) for oo, ss in zip( self.rpt_array['offset'], self.rpt_array['station'])], dtype=sdtype) offset_sort = np.sort(slist, order='offset') self.offset_list = offset_sort['offset'] self.station_list = offset_sort['station'] #min and max frequency of the plot pmin = int(np.floor(np.log10(self.freq_list.min()))) pmax = int(np.ceil(np.log10(self.freq_list.max()))) #set y-axis major ticks to be on each power of 10 self.ax.yaxis.set_ticks( np.arange(pmin * self.ystretch, (pmax + 1) * self.ystretch, self.ystretch)) #set y-ticklabels to coincide with the desired label if self.tscale == 'period': #make tick labels that will represent period yticklabels = [ mtpl.labeldict[-ii] for ii in range(pmin, pmax + 1, 1) ] self.ax.set_ylabel('Period (s)', fontsize=self.font_size + 2, fontweight='bold') elif self.tscale == 'frequency': yticklabels = [ mtpl.labeldict[ii] for ii in range(pmin, pmax + 1, 1) ] self.ax.set_ylabel('Frequency (Hz)', fontsize=self.font_size + 2, fontweight='bold') #--> set y-limits if self.ylimits == None: self.ax.set_ylim(pmin * self.ystretch, pmax * self.ystretch) else: pmin = np.log10(self.ylimits[0]) * self.ystretch pmax = np.log10(self.ylimits[1]) * self.ystretch self.ax.set_ylim(pmin, pmax) #--> set y-axis tick labels self.ax.set_yticklabels(yticklabels) #--> set x-axis label self.ax.set_xlabel('Station', fontsize=self.font_size + 2, fontweight='bold') #set x-axis ticks self.ax.set_xticks(self.offset_list * self.xstretch) #set x-axis tick labels as station names xticklabels = self.station_list if self.xstep != 1: xticklabels = np.zeros(len(self.station_list), dtype=self.station_list.dtype) for xx in range(0, len(self.station_list), self.xstep): xticklabels[xx] = self.station_list[xx] self.ax.set_xticklabels(xticklabels) #--> set x-limits if self.xlimits == None: self.ax.set_xlim(self.offset_list.min() * self.xstretch - es * 2, self.offset_list.max() * self.xstretch + es * 2) else: self.ax.set_xlim(self.xlimits) #--> set title of the plot if self.plot_title == None: pass else: self.ax.set_title(self.plot_title, fontsize=self.font_size + 2) #put a grid on the plot self.ax.grid(alpha=.25, which='both', color=(.25, .25, .25)) #==> make a colorbar with appropriate colors if self.cb_position == None: self.ax2, kw = mcb.make_axes(self.ax, orientation=self.cb_orientation, shrink=.35) else: self.ax2 = self.fig.add_axes(self.cb_position) if cmap == 'mt_seg_bl2wh2rd': #make a color list self.clist = [(cc, cc, 1) for cc in np.arange(0, 1+1./(nseg), 1./(nseg))]+\ [(1, cc, cc) for cc in np.arange(1, -1./(nseg), -1./(nseg))] #make segmented colormap mt_seg_bl2wh2rd = colors.ListedColormap(self.clist) #make bounds so that the middle is white bounds = np.arange(ckmin - ckstep, ckmax + 2 * ckstep, ckstep) #normalize the colors norms = colors.BoundaryNorm(bounds, mt_seg_bl2wh2rd.N) #make the colorbar self.cb = mcb.ColorbarBase(self.ax2, cmap=mt_seg_bl2wh2rd, norm=norms, orientation=self.cb_orientation, ticks=bounds[1:-1]) else: self.cb = mcb.ColorbarBase(self.ax2, cmap=mtcl.cmapdict[cmap], norm=colors.Normalize(vmin=ckmin, vmax=ckmax), orientation=self.cb_orientation) #label the color bar accordingly self.cb.set_label(mtpl.ckdict[ck], fontdict={ 'size': self.font_size, 'weight': 'bold' }) #place the label in the correct location if self.cb_orientation == 'horizontal': self.cb.ax.xaxis.set_label_position('top') self.cb.ax.xaxis.set_label_coords(.5, 1.3) elif self.cb_orientation == 'vertical': self.cb.ax.yaxis.set_label_position('right') self.cb.ax.yaxis.set_label_coords(1.5, .5) self.cb.ax.yaxis.tick_left() self.cb.ax.tick_params(axis='y', direction='in') plt.show()
result = eng.run(prog) wigners.append(result.state.wigner(0, x, p)) # Plotting cmax = np.real_if_close(np.amax(np.array(wigners))) cmin = np.real_if_close(np.amin(np.array(wigners))) if abs(cmin) < cmax: cmin = -cmax else: cmax = -cmin fig, axs = plt.subplots(1, 5, figsize=(16, 4), gridspec_kw={"width_ratios": [1, 1, 1, 1, 0.05]}) cmap = plt.cm.RdBu norm = colors.Normalize(vmin=cmin, vmax=cmax) cb1 = colorbar.ColorbarBase(axs[4], cmap=cmap, norm=norm, orientation="vertical") ims = np.empty(4, dtype=object) axs[0].set_ylabel(r"p (units of $\sqrt{\hbar\pi}$)", fontsize=15) axs[0].set_title(r"$|+i^\epsilon\rangle_{gkp}$, $\epsilon$=0.1 (10 dB)", fontsize=15) for i in range(4): ims[i] = axs[i].contourf( x / np.sqrt(np.pi), p / np.sqrt(np.pi), wigners[i], levels=60, cmap=plt.cm.RdBu, vmin=cmin, vmax=cmax, ) axs[i].set_xlabel(r"q (units of $\sqrt{\hbar\pi}$)", fontsize=15) if i > 0:
def plot_bandfits(self, st_exp_phasor_collection, pcc_config, n_points=500, use_degrees=True): """ Plot the fit, residuals, and the neighborhood of the local minimum found for the fit solution """ #we want to plot: #(1) the phasor data #(2) the fitted delay model solution + mid-band phase/location #(3) the phase residuals #(4) the fit function as a function of fit parameters: delay/phase #create output dir if not already there if not os.path.exists(pcc_config.output_dir): os.makedirs(pcc_config.output_dir) scale_freq = 1e9 #use GHz for freq axis factor = 1.0 if use_degrees is True: factor = 180.0 / math.pi for scan in st_exp_phasor_collection.sspc_list: for bp in scan.fit_results.keys(): if scan.fit_results[bp].valid is True: ref_freq = scan.fit_results[ bp].fit_data.reference_frequency tone_phasors = scan.fit_results[bp].fit_data.tone_phasors delay = scan.fit_results[bp].delay phase_offset = scan.fit_results[bp].phase_offset residuals = scan.fit_results[bp].residuals #get the phasor data into lists phase_arr = [] phase_err_arr = [] freq_arr = [] #this is here to make a plot of the phasor measurements during each scan count = 0 x_arr = [] y_arr = [] z_arr = [] auto_fig = plt.figure(figsize=(8.5, 11)) for x in tone_phasors: freq_arr.append(x[0]) phase_arr.append(cmath.phase(x[1]) * factor) ph_stddev = math.sqrt(x[2].get_phase_variance()) phase_err_arr.append(factor * ph_stddev) phasor_measurements = x[2].data x_arr.extend([c.real for c in phasor_measurements]) y_arr.extend([c.imag for c in phasor_measurements]) z_arr.extend([x[0] / scale_freq] * len(phasor_measurements)) cmap = cmx.get_cmap('viridis') normalize = mcolors.Normalize(vmin=min(z_arr), vmax=max(z_arr)) colors = [cmap(normalize(value)) for value in z_arr] plt.scatter(x_arr, y_arr, s=1, c=colors) plt.title("P-cal phasor measurements during scan: " + scan.scan_name + ", station: " + st_exp_phasor_collection.mk4_site_id + " band-pol:" + bp.replace(':', '-')) plt.grid(True) plt.ylabel("Imag)") plt.xlabel("Real") ax = plt.gca() cax, _ = mcbar.make_axes(ax, location='bottom', anchor=(0.5, -0.2), aspect=30) cbar = mcbar.ColorbarBase(cax, cmap=cmap, norm=normalize, orientation='horizontal') cbar.ax.set_xlabel("Frequency (GHz)") auto_fig_name = "tone-phasors-" + scan.scan_name + "." + st_exp_phasor_collection.mk4_site_id + "." + bp.replace( ':', '-') + ".png" auto_fig.savefig( os.path.join(pcc_config.output_dir, auto_fig_name)) plt.close(auto_fig) min_freq = min(freq_arr) max_freq = max(freq_arr) step = (max_freq - min_freq) / n_points #get the residuals resid_arr = [] resid_freq_arr = [] for x in residuals: resid_freq_arr.append(x[0]) resid_arr.append(x[1] * factor) #create plotting arrays of the delay models model_phase = [] model_freq = [] for n in list(range(0, n_points)): freq = min_freq + n * step phase = cmath.phase( pcc_delay_fitting.calc_delay_phasor( delay, phase_offset, ref_freq, freq)) * factor model_freq.append(freq) model_phase.append(phase) #now create a plot for this band/pol auto_fig = plt.figure(figsize=(8.5, 11)) plt.subplot(311) plt.title("Band delay-fit for scan: " + scan.scan_name + ", station: " + st_exp_phasor_collection.mk4_site_id + " band-pol:" + bp.replace(':', '-')) plt.errorbar(freq_arr, phase_arr, yerr=phase_err_arr, fmt='bo', markersize=4) plt.plot(model_freq, model_phase, 'r-') plt.grid(True) plt.ylabel("Phase (deg)") ax = plt.gca() ticks_x = ticker.FuncFormatter( lambda a, pos: '{0:g}'.format(old_div(a, scale_freq))) ax.xaxis.set_major_formatter(ticks_x) plt.xlabel("Frequency (GHz)") #residuals plt.subplot(312) plt.errorbar(resid_freq_arr, resid_arr, yerr=phase_err_arr, fmt='bo', markersize=4) plt.grid(True) plt.ylabel("Phase residuals (deg)") ax2 = plt.gca() ticks_x2 = ticker.FuncFormatter( lambda a, pos: '{0:g}'.format(old_div(a, scale_freq))) ax2.xaxis.set_major_formatter(ticks_x2) plt.xlabel("Frequency (GHz)") plt.grid(True) #now we want to create a plot of the minimization function and put #a star in the location of the minimum bd_fitter = pcc_delay_fitting.BandDelayFitter() n_points_de = 500 n_points_ph = 50 delay_window = 4e-9 x = np.zeros((n_points_de, n_points_ph)) y = np.zeros((n_points_de, n_points_ph)) z = np.zeros((n_points_de, n_points_ph)) for i in list(range(0, n_points_de)): for j in list(range(0, n_points_ph)): x[i][j] = (delay - delay_window ) + i * (2.0 * delay_window) / n_points_de y[i][j] = (-math.pi + j * 2.0 * math.pi / n_points_ph) * (old_div(180.0, math.pi)) param = [x[i][j], y[i][j] * (old_div(math.pi, 180.0))] z[i][j] = bd_fitter.fit_function1( param, scan.fit_results[bp].fit_data) plt.subplot(313) plt.contourf(x, y, z, 20) plt.ylim(-180, 180) ax3 = plt.gca() ax3.set_yticks([-180, -90, 0, 90, 180]) plt.ylabel("Phase offset at \n reference frequency (deg)") cbar = plt.colorbar(pad=0.2, orientation='horizontal') cbar.set_label('Minimization function') plt.plot(delay, phase_offset * (old_div(180.0, math.pi)), 'r+', markersize=7) ax3.annotate( ' ($t$, $\phi$) = (' + str(round(old_div(delay, pcc_delay_fitting.PICOSECOND), 2)) + ' ps, ' + str(round(phase_offset * (old_div(180.0, math.pi)), 0)) + '$^\circ$)', xy=(delay, phase_offset * (old_div(180.0, math.pi))), color='red') scale_delay = 1e-9 ticks_x3 = ticker.FuncFormatter( lambda a, pos: '{0:g}'.format(old_div(a, scale_delay))) ax3.xaxis.set_major_formatter(ticks_x3) plt.xlabel("Delay (ns)") auto_fig_name = "bandfit-" + scan.scan_name + "." + st_exp_phasor_collection.mk4_site_id + "." + bp.replace( ':', '-') + ".png" auto_fig.savefig( os.path.join(pcc_config.output_dir, auto_fig_name)) plt.close(auto_fig)
) #ra, dec should be given in degrees and radius can be adjusted gc.set_theme("publication") gc.show_colorscale(cmap='viridis', vmin=min, vmax=max) #gc.add_scalebar(0.00833333, "10\'\'") gc.add_label('ra', 'dec', '+', color='blue', size=20, layer='point') #ra, dec should be given in degrees #gc.show_contour("XXX.fits", levels=[5*rms, 10*rms, 15*rms] , colors='red', layer='cont') axisf3 = fig.add_axes([0.92, 0.1145, 0.02, 0.768]) normf3 = mc.Normalize(vmin=min, vmax=max) cbf3 = clm.ColorbarBase(axisf3, cmap='viridis', norm=normf3, orientation='vertical', format='%0.1e') cbf3.set_label('Flux (Jy/beam)', fontsize=20) gc.add_beam() gc.beam.show() gc.beam.set_color('blue') gc.beam.set_edgecolor('blue') gc.beam.set_facecolor('blue') gc.beam.set_borderpad(0) gc.beam.set_frame(True) gc.beam.set_alpha(0.5) gc.axis_labels.show() gc.tick_labels.show()
def slice3(slcfname,fields_to_draw,axis='y',extent=None,\ writefile=True,tstamp=True,field_label=True): global aux plt.rc('font', size=14) plt.rc('xtick', labelsize=14) plt.rc('ytick', labelsize=14) slc_data = pickle.load(open(slcfname, 'rb')) x0 = slc_data[axis + 'extent'][0] y0 = slc_data[axis + 'extent'][2] print x0, y0 Lx = slc_data[axis + 'extent'][1] - slc_data[axis + 'extent'][0] Ly = slc_data[axis + 'extent'][3] - slc_data[axis + 'extent'][2] if extent is None: extent = [x0, x0 + Lx, y0, y0 + Ly] x0 = extent[0] y0 = extent[2] lx = extent[1] - extent[0] ly = extent[3] - extent[2] print extent, lx, ly ix = 2 iz = ix * ly / lx nf = len(fields_to_draw) fig = plt.figure(1, figsize=(ix * nf, iz + ix * 1.2)) gs = gridspec.GridSpec(1, nf) gs.update(top=0.95, left=0.10, right=0.95, wspace=0.05, hspace=0) norm_factor = 2. starname = slcfname.replace('slice/', 'id0/').replace('slice.p', 'starpar.vtk') sp = read_starvtk(starname) if slc_data.has_key('time'): tMyr = slc_data['time'] else: time, sp = read_starvtk(starname, time_out=True) tMyr = time * Myr images = [] star_axis = -1 for j, f in enumerate(fields_to_draw): ax = plt.subplot(gs[0, j]) if f is 'star_particles': scatter_sp(sp, ax, axis=axis, norm_factor=norm_factor, type='surf') ax.set_xlim(x0, x0 + lx) ax.set_ylim(y0, y0 + ly) ax.set_aspect(1.0) star_axis = j else: data = slc_data[axis][f] im = ax.imshow(data, origin='lower', interpolation='bilinear' ) #interpolation='nearest',resample=True) if aux[f]['log']: im.set_norm(LogNorm()) im.set_extent(slc_data[axis + 'extent']) im.set_cmap(aux[f]['cmap']) im.set_clim(aux[f]['clim']) images.append(im) ax.set_xlim(extent[0], extent[1]) ax.set_ylim(extent[2], extent[3]) ax.set_aspect(1.0) for j, (im, f) in enumerate(zip(images, fields_to_draw)): if f != 'star_particles': ax = plt.subplot(gs[0, j]) divider = make_axes_locatable(ax) cax = divider.append_axes("top", "3%", pad="1%") ## cax=plt.subplot(gs[0,j]) cbar = fig.colorbar(im, cax=cax, orientation='horizontal') cbar.set_label(aux[f]['label']) cax.xaxis.tick_top() cax.xaxis.set_label_position('top') if aux[f].has_key('cticks'): cbar.set_ticks(aux[f]['cticks']) if star_axis != -1: ax = plt.subplot(gs[0, star_axis]) divider = make_axes_locatable(ax) cax = divider.append_axes("top", "3%", pad="1%") ## cax=plt.subplot(gs[0,0]) cbar = colorbar.ColorbarBase(cax, ticks=[0, 20, 40], cmap=plt.cm.cool_r, norm=Normalize(vmin=0, vmax=40), orientation='horizontal') cax.xaxis.tick_top() cax.xaxis.set_label_position('top') cbar.set_label(r'${\rm age [Myr]}$') s1 = ax.scatter(Lx * 2, Ly * 2, s=np.sqrt(1.e3) / norm_factor, color='k', alpha=.8, label=r'$10^3 M_\odot$') s2 = ax.scatter(Lx * 2, Ly * 2, s=np.sqrt(1.e4) / norm_factor, color='k', alpha=.8, label=r'$10^4 M_\odot$') s3 = ax.scatter(Lx * 2, Ly * 2, s=np.sqrt(1.e5) / norm_factor, color='k', alpha=.8, label=r'$10^5 M_\odot$') ax.set_xlim(x0, x0 + lx) ax.set_ylim(y0, y0 + ly) legend = ax.legend( (s1, s2, s3), (r'$10^3 M_\odot$', r'$10^4 M_\odot$', r'$10^5 M_\odot$'), scatterpoints=1, loc='lower left', fontsize='medium', frameon=True) axes = fig.axes plt.setp([ax.get_xticklabels() for ax in axes[:nf]], visible=False) plt.setp([ax.get_yticklabels() for ax in axes[:nf]], visible=False) plt.setp(axes[:nf], 'xlim', (x0, x0 + lx)) plt.setp(axes[:nf], 'ylim', (y0, y0 + ly)) plt.setp(axes[0], 'xlabel', 'x [kpc]') plt.setp(axes[0], 'ylabel', 'z [kpc]') if tstamp: ax = axes[0] ax.text(0.5, 0.95, 't=%3d Myr' % tMyr, size=16, horizontalalignment='center', transform=ax.transAxes, **(texteffect())) # axes[0].text(x0*0.9,y0*0.9, # 't=%3d Myr' % tMyr,ha='left',va='top',**(texteffect(16))) # plt.setp(axes[0],'title','t=%3d Myr' % tMyr) plt.setp([ax.get_xticklabels() for ax in axes[:nf:nf]], visible=True) plt.setp([ax.get_yticklabels() for ax in axes[:nf:nf]], visible=True) plt.setp([ax.xaxis.get_majorticklabels() for ax in axes[:nf:nf]], rotation=45) pngfname = slcfname + '.png' #canvas = mpl.backends.backend_agg.FigureCanvasAgg(fig) #canvas.print_figure(pngfname,num=1,dpi=150,bbox_inches='tight') if writefile: plt.savefig(pngfname, bbox_inches='tight', num=0, dpi=150) plt.close() else: return fig
def visualize_stereo_map( coordinates, values, min_va, max_va, markersize=75, fillconts="grey", fillsea="white", labplot="", plottype="scatter", make_caxes=True, cmap=plt.cm.viridis, set_in_ax=None, centercm=False, resample_time=None, ): """ Visualize data on a polar stereographic projection map using cartopy on matplotlib. :param coordinates: give geographical coordinates of the points to plot :param values: can be a 1D vector of values (and a colormap is build accordingly) or it can be a 2D vector Nx3 corresponding to some colormap to be used for each datapoint :param fillconts: color to fill continents :param fillsea: color to fill seas :param labplot: the label for the data series, to use for legend and other handles :param min_va: min values to clip lower values (should be min of the series) :param max_va: max values to clip lower values (should be max of the series) :param plottype: (BETA) use different plotting tools (scatter or plot so far) :returns ax: figure handle. :returns ax: axes handles of the caropy map. :returns cbar: handle to the colorbar .. todo:: fix colors for plot as in scatter, but color lines rather than pointsself. .. todo:: add support for *custom* background image (e.g. sea surface temperature, wind magnitude, etc.) (use something.contourf() to interpolate linearly within a grid of values at known coordinates?) .. todo: add support for geo-unreferenced basemaps .. note:: The longitude lon_0 is at 6-o'clock, and the latitude circle boundinglat is tangent to the edge of the map at lon_0. Default value of lat_ts (latitude of true scale) is pole. .. note:: Latitude is in °N, longitude in is °E """ from matplotlib.colors import ListedColormap from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter from matplotlib.path import Path as mpath gps = coordinates.copy() # print(values.describe()) tr1 = np.median(np.diff(coordinates.index.tolist())) tr2 = np.median(np.diff(values.index.tolist())) min_tres = max(tr1, tr2) min_tres = int(min_tres.total_seconds() / 60) # print(u"matching resolution @ %i minutes"%min_tres) values = pd.DataFrame(data=values.values, index=values.index, columns=["value"]) values.index.name = "timest_" coordinates = dataset.ts_aggregate_timebins( coordinates, time_bin=min_tres, operations={"": np.nanmedian}, index_position="middle", ) values = dataset.ts_aggregate_timebins(values, time_bin=min_tres, operations={"": np.nanmean}, index_position="middle") # values[values > max_va] = max_va # values[values < min_va] = min_va if resample_time == None: resample_time = min_tres toplot = pd.concat((coordinates, values), axis=1) toplot = dataset.ts_aggregate_timebins( toplot, time_bin=resample_time, operations={"": np.nanmedian}, index_position="middle", ) toplot = toplot.dropna() ortho = ccrs.SouthPolarStereo() # # ortho = ccrs.Orthographic(central_longitude=0, central_latitude=-90) geo = ccrs.Geodetic() # ortho = ccrs.Orthographic(central_longitude=0, central_latitude=-90) # geo = ccrs.Geodetic() # prepare basemap if set_in_ax is None: # fig = plt.gcf() # ortho = ccrs.Orthographic(central_longitude=0, central_latitude=-90) # geo = ccrs.Geodetic() fig = plt.figure() ax = fig.add_subplot(111, projection=ortho) else: fig = set_in_ax[0] shax = set_in_ax[1] ax = fig.add_subplot( shax.shape[0], shax.shape[1], np.where(np.ravel(shax))[0][0] + 1, projection=ortho, ) ax.set_extent([-180, 180, -90, -35], ccrs.PlateCarree()) ax.coastlines(linewidth=1.5) ax.add_feature(cfeature.LAND, facecolor=fillconts) ax.add_feature(cfeature.OCEAN, facecolor=fillsea) # ax.gridlines(color='black', linestyle='--', alpha=0.5) # m.shadedrelief() # prepare colors if not hasattr(cmap, "shape"): if centercm: th_ = -np.max((np.abs(min_va), max_va)), np.max( (np.abs(min_va), max_va)) else: th_ = min_va, max_va normalize = mpl.colors.Normalize(vmin=th_[0], vmax=th_[1]) # cmap = mpl.cm.LinearSegmentedColormap( # [cmap(normalize(value)) for value in toplot.iloc[:, -1]] # ) else: cmap = ListedColormap(cmap) from cartopy.mpl.gridliner import LATITUDE_FORMATTER, LONGITUDE_FORMATTER if plottype == "scatter": ax.plot( gps.iloc[:, 1], gps.iloc[:, 0], transform=geo, linewidth=1, color="black", zorder=1, ) ax.scatter( toplot.iloc[:, 1].values, toplot.iloc[:, 0].values, transform=geo, c=toplot.iloc[:, 2].values, s=markersize, alpha=0.75, linewidth=0, label=labplot, cmap=cmap, zorder=2, ) # , norm=norm # theta = np.linspace(0, 2*np.pi, 100) # center, radius = [0.5, 0.5], 0.5 # verts = np.vstack([np.sin(theta), np.cos(theta)]).T # circle = mpath(verts * radius + center) # ax.set_boundary(circle, transform=ax.transAxes) ax.gridlines(draw_labels=True, linewidth=0.5, color="gray", alpha=0.5, linestyle="-") # crs=ccrs.PlateCarree(), # Define gridline locations and draw the lines using cartopy's built-in gridliner: # xticks = [-110, -50, -40, -30, -20, -11, 0, 10, 20, 30, 40, 50] # yticks = [10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80] # ax.gridlines(xlocs=xticks, ylocs=yticks) # Label the end-points of the gridlines using the custom tick makers: # ax.xaxis.set_major_formatter(LONGITUDE_FORMATTER) # ax.yaxis.set_major_formatter(LATITUDE_FORMATTER) # lambert_xticks(ax, xticks) # lambert_yticks(ax, yticks) # ax.set_xticks([0, 60, 120, 180, 240, 300, 360], crs=ccrs.PlateCarree()) # ax.set_yticks([-90, -60, -30, 0, 30, 60, 90], crs=ccrs.PlateCarree()) # lon_formatter = LongitudeFormatter(zero_direction_label=True) # lat_formatter = LatitudeFormatter() # ax.xaxis.set_major_formatter(lon_formatter) # ax.yaxis.set_major_formatter(lat_formatter) # import matplotlib.ticker as mticker # grid lines # gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, # linewidth=0.5, color='gray', alpha=0.5, linestyle='-') # gl.ylocator = mticker.FixedLocator(np.array([-180, 180, -90, -35])) # gl.xlocator = mticker.FixedLocator(np.linspace(0,360,13,dtype=int)) # ax.gridlines(crs = ccrs.PlateCarree(),color='lightgrey', linestyle='-', draw_labels=True) elif plottype == "plot": ax.plot( coordinates.iloc[:, 1].values, coordinates.iloc[:, 0].values, transform=ccrs.PlateCarree(), color=cmap, s=markersize, linewidth=0, label=labplot, ) # im = m.plot(lon,lat,color=colors,linewidth=markersize,label=labplot) else: print("unrecognized plot") return -1 # ax.set_title(labplot,fontsize=35) if make_caxes: cax, _ = clb.make_axes(ax) cbar = clb.ColorbarBase(cax, cmap=cmap, norm=normalize) return fig, ax, cbar else: return fig, ax
# build custom pole figures pf = PoleFigure(microstructure=micro) pf.mksize = 40 pf.set_map_field('strain', strain_field, field_min_level=0.015, field_max_level=0.025) fig = plt.figure() # direct PF ax1 = fig.add_axes([0.05, 0.05, 0.8, 0.9], aspect='equal') pf.plot_pf(ax=ax1) plt.title('111 pole figure, cubic elasticity') # to add the color bar ax2 = fig.add_axes([0.8, 0.05, 0.05, 0.9]) norm = colors.Normalize(vmin=0.015, vmax=0.025) cb = colorbar.ColorbarBase(ax2, cmap=cm.hot, norm=norm, orientation='vertical') cb.set_label('Average strain (mm/mm)') image_name = os.path.splitext(__file__)[0] + '.png' print('writting %s' % image_name) plt.savefig('%s' % image_name, format='png') from matplotlib import image image.thumbnail(image_name, 'thumb_' + image_name, 0.2)
def slice(slcfname,starfname,fields_to_draw,zoom=1.,aux={},\ writefile=True,tstamp=True,stars=True,field_label=True,norm_factor=2): plt.rc('font', size=14) plt.rc('xtick', labelsize=14) plt.rc('ytick', labelsize=14) slc_data = pickle.load(open(slcfname, 'rb')) x0 = slc_data['yextent'][0] y0 = slc_data['yextent'][3] Lx = slc_data['yextent'][1] - slc_data['yextent'][0] Lz = slc_data['yextent'][3] - slc_data['yextent'][2] Lz = Lz / zoom ix = 2 iz = ix * Lz / Lx nf = len(fields_to_draw) fig = plt.figure(1, figsize=(ix * nf, iz + ix * 2)) gs = gridspec.GridSpec(2, nf, height_ratios=[iz, ix]) gs.update(left=0.10, right=0.90, wspace=0, hspace=0) sp = read_starvtk(starfname) if 'time' in slc_data: tMyr = slc_data['time'] else: time, sp = read_starvtk(starfname, time_out=True) tMyr = time * Myr images = [] for i, axis in enumerate(['y', 'z']): for j, f in enumerate(fields_to_draw): data = slc_data[axis][f] ax = plt.subplot(gs[i, j]) im = ax.imshow(data, origin='lower') if f in aux: if 'norm' in aux[f]: im.set_norm(aux[f]['norm']) if 'cmap' in aux[f]: im.set_cmap(aux[f]['cmap']) if 'clim' in aux[f]: im.set_clim(aux[f]['clim']) extent = slc_data[axis + 'extent'] im.set_extent(extent) images.append(im) if stars: if j == 0: scatter_sp(sp, ax, axis=axis, runaway=False, norm_factor=norm_factor) elif j == 1: scatter_sp(sp, ax, axis=axis, norm_factor=norm_factor) ax.set_xlim(extent[0], extent[1]) ax.set_ylim(extent[2], extent[3]) gs2 = gridspec.GridSpec(nf + 2 + stars, 1) gs2.update(left=0.91, right=0.93, hspace=0.05) for j, (im, f) in enumerate(zip(images, fields_to_draw)): cax = plt.subplot(gs2[j + stars]) cbar = fig.colorbar(im, cax=cax, orientation='vertical') if f in aux: if 'label' in aux[f]: cbar.set_label(aux[f]['label']) if 'cticks' in aux[f]: cbar.set_ticks(aux[f]['cticks']) if stars: cax = plt.subplot(gs2[0]) cbar = colorbar.ColorbarBase(cax, ticks=[0, 20, 40], cmap=plt.cm.cool_r, norm=Normalize(vmin=0, vmax=40), orientation='vertical') cbar.set_label(r'${\rm age [Myr]}$') axes = fig.axes[:2 * nf] if field_label: for ax, f in zip(axes[:nf], fields_to_draw): if f in aux: if 'label' in aux[f]: lab = aux[f]['label'] label = lab[:lab.rfind(r'\;')] + '$' ax.text(0.5, 0.95, label, size=20, horizontalalignment='center', transform=ax.transAxes, **(texteffect())) if stars: s1 = ax.scatter(Lx * 2, Lz * 2, s=np.sqrt(1.e3) / norm_factor, color='k', alpha=.8, label=r'$10^3 M_\odot$') s2 = ax.scatter(Lx * 2, Lz * 2, s=np.sqrt(1.e4) / norm_factor, color='k', alpha=.8, label=r'$10^4 M_\odot$') s3 = ax.scatter(Lx * 2, Lz * 2, s=np.sqrt(1.e5) / norm_factor, color='k', alpha=.8, label=r'$10^5 M_\odot$') ax.set_xlim(x0, x0 + Lx) ax.set_ylim(y0, y0 + Lz) legend = ax.legend( (s1, s2, s3), (r'$10^3 M_\odot$', r'$10^4 M_\odot$', r'$10^5 M_\odot$'), scatterpoints=1, loc='lower left', fontsize='medium', frameon=True) plt.setp([ax.get_xticklabels() for ax in axes[:2 * nf]], visible=False) plt.setp([ax.get_yticklabels() for ax in axes[:2 * nf]], visible=False) plt.setp(axes[:nf], 'ylim', (slc_data['yextent'][2] / zoom, slc_data['yextent'][3] / zoom)) plt.setp(axes[nf:2 * nf], 'xlabel', 'x [kpc]') plt.setp(axes[0], 'ylabel', 'z [kpc]') if tstamp: plt.setp(axes[0], 'title', 't=%3d Myr' % tMyr) plt.setp(axes[nf], 'ylabel', 'y [kpc]') plt.setp([ax.get_xticklabels() for ax in axes[nf:]], visible=True) plt.setp([ax.get_yticklabels() for ax in axes[:2 * nf:nf]], visible=True) plt.setp([ax.xaxis.get_majorticklabels() for ax in axes[nf:2 * nf]], rotation=45) pngfname = slcfname[:-1] + 'png' #canvas = mpl.backends.backend_agg.FigureCanvasAgg(fig) #canvas.print_figure(pngfname,num=1,dpi=150,bbox_inches='tight') if writefile: plt.savefig(pngfname, bbox_inches='tight', num=1, dpi=150) plt.close(1) else: return fig
# Choose color based on value colorRGB = cmap((c-vmin)/(vmax-vmin))[:3] # Add the shape to the axes # county.geometry is an object that contains the x/y coordinates. ax.add_geometries([county.geometry], ccrs.PlateCarree(),facecolor = colorRGB, edgecolor = 'gray',linewidth=0.5) # Create a colorbar # Create a new axes on the figure [x,y,width,height] # Change these settings to move its position or changes its size axCB = fig.add_axes([0.85, 0.20, 0.04, 0.56]) norm = colors.Normalize(vmin=vmin, vmax = vmax) cb = colorbar.ColorbarBase(ax=axCB, cmap =cmap, norm = norm, spacing='uniform', orientation='vertical' ) cb.set_label('Index',fontweight = 'bold') # # Map grid lines (lots of fine-tuning your map) # gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, linewidth=0.5, color='gray', alpha=0.5, linestyle='--') gl.xlabels_top = False gl.ylabels_right = False gl.xlines = True gl.xlocator = mticker.FixedLocator([-94, -95, -96,-97,-98]) gl.ylocator = mticker.FixedLocator([38,39,40])
def plot_slice_proj(fname_slc, fname_proj, fname_sp, fields_to_draw, savname=None, zoom=1., aux={}, time_stamp=True, fig_zmargin=0.5, sp_norm_factor=2): """ Draw slices and projections """ plt.rc('font', size=13) plt.rc('xtick', labelsize=14) plt.rc('ytick', labelsize=14) slc_data = pickle.load(open(fname_slc, 'rb')) proj_data = pickle.load(open(fname_proj, 'rb')) for x in ('x', 'y', 'z'): slc_data[x + 'extent'] = np.array(slc_data[x + 'extent']) / 1e3 slc_data[x + 'yextent'] = np.array(slc_data[x + 'extent']) / 1e3 slc_data[x + 'xextent'] = np.array(slc_data[x + 'extent']) / 1e3 # starting position x0 = slc_data['xextent'][0] y0 = slc_data['xextent'][1] Lx = slc_data['yextent'][1] - slc_data['yextent'][0] Ly = slc_data['zextent'][1] - slc_data['zextent'][0] Lz = slc_data['yextent'][3] - slc_data['yextent'][2] # print('x0,y0,Lx,Ly,Lz:', x0, y0, Lx, Ly, Lz) # Set figure size in inches and margins Lz = Lz / zoom xsize = 3.0 zsize = xsize * Lz / Lx nf = len(fields_to_draw) # print('xsize,zsize', xsize,zsize) # Need to adjust zmargin depending on number of fields and aspect_ratio zfactor = 1.0 + fig_zmargin fig = plt.figure(1, figsize=(xsize * nf, zsize + xsize * zfactor)) gs = gridspec.GridSpec(2, nf, height_ratios=[zsize, xsize]) gs.update(top=0.95, left=0.10, right=0.95, wspace=0.05, hspace=0) # Read starpar and time time_sp, sp = read_starvtk(fname_sp, time_out=True) if 'time' in slc_data: tMyr = slc_data['time'] else: tMyr = time_sp * to_Myr # Sanity check if np.abs(slc_data['time'] / (time_sp * to_Myr) - 1.0) > 1e-7: print('[plot_slice_proj]: Check time time_slc, time_sp', tMyr, time_sp * to_Myr) #raise images = [] for i, axis in enumerate(['y', 'z']): for j, f in enumerate(fields_to_draw): ax = plt.subplot(gs[i, j]) if f == 'star_particles': scatter_sp(sp, ax, axis=axis, norm_factor=sp_norm_factor, type='surf') # if axis == 'y': # ax.set_xlim(x0, x0 + Lx) # ax.set_ylim(y0, y0 + Lz) # if axis == 'z': # ax.set_xlim(x0, x0 + Lx) # ax.set_ylim(x0, x0 + Lx) extent = slc_data[axis + 'extent'] # print(axis,extent) ax.set_xlim(extent[0], extent[1]) ax.set_ylim(extent[2], extent[3]) ax.set_aspect(1.0) else: if f[-4:] == 'proj': data = proj_data[axis][f[:-5]] # if f == 'rho_proj': # Plot mean nH rather than Sigma_gas # if axis == 'y': # Sunit_conv = ((1.0*au.Msun/au.pc**2/(unit['muH'])).to('cm**-2')).cgs.value # data *= Sunit_conv # data /= (1.0*au.pc).cgs.value*(Ly*1e3) # if axis == 'z': # Sunit_conv = ((1.0*au.Msun/au.pc**2/(unit['muH'])).to('cm**-2')).cgs.value # data *= Sunit_conv # data /= (1.0*au.pc).cgs.value*(Lz*1e3) else: data = slc_data[axis][f] im = ax.imshow(data, origin='lower', interpolation='bilinear') if f in aux: if 'norm' in aux[f]: im.set_norm(aux[f]['norm']) if 'cmap' in aux[f]: im.set_cmap(aux[f]['cmap']) if 'clim' in aux[f]: im.set_clim(aux[f]['clim']) extent = slc_data[axis + 'extent'] im.set_extent(extent) images.append(im) ax.set_xlim(extent[0], extent[1]) ax.set_ylim(extent[2], extent[3]) for j, (im, f) in enumerate(zip(images, fields_to_draw[1:])): ax = plt.subplot(gs[0, j + 1]) divider = make_axes_locatable(ax) cax = divider.append_axes("top", "3%", pad="1%") cbar = fig.colorbar(im, cax=cax, orientation='horizontal') if f in aux: if 'label' in aux[f]: cbar.set_label(aux[f]['label']) if 'cticks' in aux[f]: cbar.set_ticks(aux[f]['cticks']) cax.xaxis.tick_top() cax.xaxis.set_label_position('top') # https://pythonmatplotlibtips.blogspot.com/2018/10/draw-second-colorbar-axis-outside-first-axis.html # if f == 'rho_proj': # pos = cbar.ax.get_position() # print(pos) # ax1 = cbar.ax # # create a second axis and specify ticks based on the relation between the first axis and second aces # ax2 = ax1.twinx() # print(ax2.get_position()) # #ax2.set_ylim([1.0, 100.0]) # #pos.y1 -= 0.08 # #ax1.set_position(pos) # #ax2.set_position(pos) ax = plt.subplot(gs[0, 0]) divider = make_axes_locatable(ax) cax = divider.append_axes("top", "3%", pad="1%") cbar = colorbar.ColorbarBase(cax, ticks=[0, 20, 40], cmap=plt.cm.cool_r, norm=Normalize(vmin=0, vmax=40), orientation='horizontal') cax.xaxis.tick_top() cax.xaxis.set_label_position('top') cbar.set_label(r'${\rm age [Myr]}$') s1 = ax.scatter(Lx * 2, Lz * 2, s=np.sqrt(1.e3) / sp_norm_factor, color='k', alpha=.8, label=r'$10^3 M_\odot$') s2 = ax.scatter(Lx * 2, Lz * 2, s=np.sqrt(1.e4) / sp_norm_factor, color='k', alpha=.8, label=r'$10^4 M_\odot$') s3 = ax.scatter(Lx * 2, Lz * 2, s=np.sqrt(1.e5) / sp_norm_factor, color='k', alpha=.8, label=r'$10^5 M_\odot$') #ax.set_xlim(x0, x0 + Lx) #ax.set_ylim(y0, y0 + Lz) legend = ax.legend( (s1, s2, s3), (r'$10^3 M_\odot$', r'$10^4 M_\odot$', r'$10^5 M_\odot$'), scatterpoints=1, loc='lower left', fontsize='medium', frameon=True) axes = fig.axes plt.setp([ax.get_xticklabels() for ax in axes[:2 * nf]], visible=False) plt.setp([ax.get_yticklabels() for ax in axes[:2 * nf]], visible=False) plt.setp(axes[:nf], 'ylim', (slc_data['yextent'][2] / zoom, slc_data['yextent'][3] / zoom)) plt.setp(axes[nf:2 * nf], 'xlabel', 'x [kpc]') plt.setp(axes[0], 'ylabel', 'z [kpc]') if time_stamp: ax = axes[0] ax.text(0.5, 0.95, 't={0:3d} Myr'.format(int(tMyr)), size=16, horizontalalignment='center', transform=ax.transAxes, **(texteffect())) plt.setp(axes[nf], 'ylabel', 'y [kpc]') plt.setp([ax.get_xticklabels() for ax in axes[nf:]], visible=True) plt.setp([ax.get_yticklabels() for ax in axes[:2 * nf:nf]], visible=True) plt.setp([ax.xaxis.get_majorticklabels() for ax in axes[nf:2 * nf]], rotation=45) #pngfname=fname_slc+'ng' #canvas = mpl.backends.backend_agg.FigureCanvasAgg(fig) #canvas.print_figure(pngfname,num=1,dpi=150,bbox_inches='tight') if savname is None: return fig else: plt.savefig(savname, bbox_inches='tight', num=0, dpi=150) plt.close()
def plot_eq_disps_horiz(disp_file): # Read displacement data disp_data = np.genfromtxt(disp_file, dtype=[('lon', 'f8'), ('lat', 'f8'), ('z', 'f8'), ('eU', 'f8'), ('nV', 'f8')]) save_file_prefix = os.path.splitext(disp_file)[0] + "_disp" # Data ranges lon_min, lon_max = disp_data['lon'].min(), disp_data['lon'].max() lat_min, lat_max = disp_data['lat'].min(), disp_data['lat'].max() mean_lat = 0.5 * (lat_min + lat_max) mean_lon = 0.5 * (lon_min + lon_max) lon_range = lon_max - lon_min lat_range = lat_max - lat_min # Reshape into matrices Ncols = len(np.unique(disp_data['lon'])) Nrows = len(np.unique(disp_data['lat'])) X = disp_data['lon'].reshape(Nrows, Ncols) Y = disp_data['lat'].reshape(Nrows, Ncols) Z = disp_data['z'].reshape(Nrows, Ncols) eU = disp_data['eU'].reshape(Nrows, Ncols) nV = disp_data['nV'].reshape(Nrows, Ncols) cmap = plt.get_cmap('seismic') z_min, z_max = disp_data['z'].min(), disp_data['z'].max() z_lim = max(np.abs(z_min), np.abs(z_max)) normz = mcolor.Normalize(vmin=-z_lim, vmax=z_lim) #LEVELSz = np.concatenate((-1*np.logspace(-3, np.log10(z_lim), 6)[::-1], np.logspace(-3, np.log10(z_lim), 6))) LEVELSz = np.concatenate( (-1 * np.linspace(0.01, z_lim, 6)[::-1], np.linspace(0.01, z_lim, 6))) e_min, e_max = disp_data['eU'].min(), disp_data['eU'].max() e_lim = max(np.abs(e_min), np.abs(e_max)) norme = mcolor.Normalize(vmin=-e_lim, vmax=e_lim) #LEVELSe = np.concatenate((-1*np.logspace(-3, np.log10(e_lim), 6)[::-1], np.logspace(-3, np.log10(e_lim), 6))) LEVELSe = np.concatenate( (-1 * np.linspace(0.01, e_lim, 6)[::-1], np.linspace(0.01, e_lim, 6))) n_min, n_max = disp_data['nV'].min(), disp_data['nV'].max() n_lim = max(np.abs(n_min), np.abs(n_max)) normn = mcolor.Normalize(vmin=-n_lim, vmax=n_lim) #LEVELSn = np.concatenate((-1*np.logspace(-3, np.log10(n_lim), 6)[::-1], np.logspace(-3, np.log10(n_lim), 6))) LEVELSn = np.concatenate( (-1 * np.linspace(0.01, n_lim, 6)[::-1], np.linspace(0.01, n_lim, 6))) interp = 'cubic' landcolor = '#FFFFCC' framelabelfont = mfont.FontProperties(family='Arial', style='normal', variant='normal', size=14) # Initialize the frame and axes fig = plt.figure(0) m = Basemap(projection='cyl', llcrnrlat=lat_min, urcrnrlat=lat_max, llcrnrlon=lon_min, urcrnrlon=lon_max, lat_0=mean_lat, lon_0=mean_lon, resolution='h') m.ax = fig.add_subplot(111) m.drawmeridians(np.linspace(lon_min, lon_max, num=5.0), labels=[0, 0, 0, 1], linewidth=0) m.drawparallels(np.linspace(lat_min, lat_max, num=5.0), labels=[1, 0, 0, 0], linewidth=0) m.drawcoastlines(linewidth=0.5) m.fillcontinents(color=landcolor, zorder=0) # Colorbar divider = make_axes_locatable(m.ax) cbar_ax = divider.append_axes("right", size="5%", pad=0.05) plt.figtext(0.96, 0.7, r'Vertical disp $[m]$', rotation='vertical', fontproperties=framelabelfont) cbz = mcolorbar.ColorbarBase(cbar_ax, cmap=cmap, norm=normz) # Masked array via conditional, don't color the land unless it has water on it zero_below = int(len(LEVELSz) / 2) - 1 zero_above = zero_below + 1 masked_data = np.ma.masked_where( np.logical_and(np.array(Z <= LEVELSz[zero_above]), np.array(Z >= LEVELSz[zero_below])), Z) # Set masked pixels to the land color cmap.set_bad(landcolor, 0.0) # set alpha=0.0 for transparent # Plot the contours m.contourf(X, Y, masked_data, LEVELSz, cmap=cmap, norm=normz, extend='both', zorder=1) plt.savefig(save_file_prefix + '_z.png', dpi=100) # Initialize the frame and axes fig = plt.figure(1) m = Basemap(projection='cyl', llcrnrlat=lat_min, urcrnrlat=lat_max, llcrnrlon=lon_min, urcrnrlon=lon_max, lat_0=mean_lat, lon_0=mean_lon, resolution='h') m.ax = fig.add_subplot(111) m.drawmeridians(np.linspace(lon_min, lon_max, num=5.0), labels=[0, 0, 0, 1], linewidth=0) m.drawparallels(np.linspace(lat_min, lat_max, num=5.0), labels=[1, 0, 0, 0], linewidth=0) m.drawcoastlines(linewidth=0.5) m.fillcontinents(color=landcolor, zorder=0) # Colorbar divider = make_axes_locatable(m.ax) cbar_ax = divider.append_axes("right", size="5%", pad=0.05) plt.figtext(0.96, 0.7, r'East disp $[m]$', rotation='vertical', fontproperties=framelabelfont) cbe = mcolorbar.ColorbarBase(cbar_ax, cmap=cmap, norm=norme) # Masked array via conditional, don't color the land unless it has water on it zero_below = int(len(LEVELSe) / 2) - 1 zero_above = zero_below + 1 masked_data = np.ma.masked_where( np.logical_and(np.array(eU <= LEVELSe[zero_above]), np.array(eU >= LEVELSe[zero_below])), eU) # Set masked pixels to the land color cmap.set_bad(landcolor, 0.0) # set alpha=0.0 for transparent # Plot the contours m.contourf(X, Y, masked_data, LEVELSe, cmap=cmap, norm=norme, extend='both', zorder=1) plt.savefig(save_file_prefix + '_e.png', dpi=100) # Initialize the frame and axes fig = plt.figure(2) m = Basemap(projection='cyl', llcrnrlat=lat_min, urcrnrlat=lat_max, llcrnrlon=lon_min, urcrnrlon=lon_max, lat_0=mean_lat, lon_0=mean_lon, resolution='h') m.ax = fig.add_subplot(111) m.drawmeridians(np.linspace(lon_min, lon_max, num=5.0), labels=[0, 0, 0, 1], linewidth=0) m.drawparallels(np.linspace(lat_min, lat_max, num=5.0), labels=[1, 0, 0, 0], linewidth=0) m.drawcoastlines(linewidth=0.5) m.fillcontinents(color=landcolor, zorder=0) # Colorbar divider = make_axes_locatable(m.ax) cbar_ax = divider.append_axes("right", size="5%", pad=0.05) plt.figtext(0.96, 0.7, r'North disp $[m]$', rotation='vertical', fontproperties=framelabelfont) cbn = mcolorbar.ColorbarBase(cbar_ax, cmap=cmap, norm=normn) # Masked array via conditional, don't color the land unless it has water on it zero_below = int(len(LEVELSn) / 2) - 1 zero_above = zero_below + 1 masked_data = np.ma.masked_where( np.logical_and(np.array(nV <= LEVELSn[zero_above]), np.array(nV >= LEVELSn[zero_below])), nV) # Set masked pixels to the land color cmap.set_bad(landcolor, 0.0) # set alpha=0.0 for transparent # Plot the contours m.contourf(X, Y, masked_data, LEVELSn, cmap=cmap, norm=normn, extend='both', zorder=1) plt.savefig(save_file_prefix + '_n.png', dpi=100) print("Saved to " + save_file)
def go(): ''' Test simple roadmap following example ''' roadmap = Roadmap({ (4, 0): [(8, 4)], (8, 4): [(4, 8)], (4, 8): [(0, 4), (8, 12)], (0, 4): [(4, 0)], (8, 12): [(4, 16)], (4, 16): [(0, 12)], (0, 12): [(4, 8)] }) policy = { (4, 8): (8, 12) } # dict of intersection nodes with corresponding choice plt.close('all') fig = plt.figure() ax2 = fig.add_axes([0.8, 0.05, 0.05, 0.85]) import matplotlib.animation as manim FFMpegWriter = manim.writers['ffmpeg'] writer = FFMpegWriter(fps=10, metadata={'title': 'Collision Prob Test'}) ax1 = fig.add_axes([0.05, 0.05, 0.75, 0.85]) plt.title('Collision probability') roadmap.plot() plt.autoscale() plt.axis('square') # Obstacle and car shape, mean, covariance setup obstacle = geometry.box(0, 0, 1.5, 1) obstacle = affinity.translate(obstacle, -0.5, -0.5) # shift so back axle at origin # Make a rotated convariance matrix obst_cov = np.array([[4e-1, 0], [0, 2e-1]]) theta = -np.pi / 4 R = lambda theta: np.array([[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]]) obst_cov = np.dot(np.dot(R(theta), obst_cov), R(theta).T) obst_mu = np.array([5.5, 12.]) # mean obstacle position gamma_mu = -np.pi / 4 # mean obstacle orientation gamma_sd = 0.5 # obstacle orientation std dev # obstacle display polygon disp_obst = affinity.rotate(obstacle, gamma_mu, origin=(0, 0), use_radians=True) disp_obst = affinity.translate(disp_obst, obst_mu[0], obst_mu[1]) #cove.plot_cov_ellipse(obst_cov, obst_mu, alpha=1.0, zorder=1) covh.plot_cov_heatmap(obst_cov, obst_mu, alpha=1.0, zorder=-5, cmap=cm.gray_r) plt.gca().add_patch( plt.Polygon(np.array(disp_obst.boundary), fc='w', lw=2, alpha=0.4, zorder=5)) # Set up vehicle instance vehicle_z0 = np.array([5, 3, np.pi / 4, 0.0]).T v = Vehicle4d(vehicle_z0, geometry.box(-0.5, -0.5, 1.0, 0.5), roadmap, policy, plot_lookahead=False, cmap=cm.hot) # Add colorbar, make sure to specify tick locations to match desired ticklabels cbar = cb.ColorbarBase(ax2, cmap=cm.hot) # Simulate coll_probs = [] #with writer.saving(fig, 'Trajectory Collision Test.mp4', 200): for i in range(200): p_coll = coll_prob(v._p, obstacle, v._z[0:2], v._z[2], obst_mu, obst_cov, gamma_mu, gamma_sd) coll_probs.append(p_coll) v.plot(plt.gca(), prob=p_coll) #plt.title(str(i)) #writer.grab_frame() print i plt.pause(0.001) v.move(0.2) plt.figure() plt.plot(coll_probs)
def make_grid_animation(self, FPS, DPI, zminmax=None, doBasemap=False): save_file = self.save_file_prefix + "_grid.mp4" # Keep the data from each time step in netCDF variable form, and slice into it as needed level_ncVar = self.sim_data.variables['level'] height_ncVar = self.sim_data.variables['height'] alt_ncVar = self.sim_data.variables['altitude'] # Get ranges N_STEP = len(self.times) z_min = np.inf z_max = -np.inf z_avs = [] for i, levelstep in enumerate(level_ncVar): masked_data = np.ma.masked_where(height_ncVar[i] == 0.0000, levelstep) z_min = min(masked_data.min(), z_min) z_max = max(masked_data.max(), z_max) z_avs.append(masked_data.mean()) z_max = np.max( np.ma.masked_where(height_ncVar[0] == 0.0000, level_ncVar[0])) print("min: {}, max: {}, av: {}".format(z_min, z_max, np.array(z_avs).mean())) if (zminmax != None): z_min, z_max = zminmax # Initialize movie writing stuff FFMpegWriter = manimation.writers['ffmpeg'] metadata = dict(title='TsunamiSquares', artist='Matplotlib', comment='Animation') writer = FFMpegWriter(fps=FPS, metadata=metadata, bitrate=1000) # Initialize the frame and axes fig = plt.figure() if not doBasemap: ax = fig.add_subplot(111) plt.xlim(self.minlon, self.maxlon) plt.ylim(self.minlat, self.maxlat) #ax.get_xaxis().get_major_formatter().set_useOffset(False) #ax.get_yaxis().get_major_formatter().set_useOffset(False) else: m = Basemap(projection='cyl', llcrnrlat=self.minlat, urcrnrlat=self.maxlat, llcrnrlon=self.minlon, urcrnrlon=self.maxlon, lat_0=self.meanlat, lon_0=self.meanlon, resolution='h') m.drawmeridians(np.linspace(self.minlon, self.maxlon, num=5.0), labels=[0, 0, 0, 1], linewidth=0) m.drawparallels(np.linspace(self.minlat, self.maxlat, num=5.0), labels=[1, 0, 0, 0], linewidth=0) m.drawcoastlines(linewidth=0.5) m.ax = fig.add_subplot(111) ax = m.ax # Colorbar cmap = plt.get_cmap('Blues_r') landcolor = 'orange' #'black'#'#FFFFCC' cmap.set_bad(landcolor, 1.0) norm = mcolor.Normalize(vmin=z_min, vmax=z_max) divider = make_axes_locatable(ax) cbar_ax = divider.append_axes("right", size="5%", pad=0.05) cb = mcolorbar.ColorbarBase(cbar_ax, cmap=cmap, norm=norm) framelabelfont = mfont.FontProperties(style='normal', variant='normal', size=14) plt.figtext(0.95, 0.7, r'water altitude $[m]$', rotation='vertical', fontproperties=framelabelfont) surface = None with writer.saving(fig, save_file, DPI): for index in range(int(N_STEP)): # Get the subset of data corresponding to current time this_level = level_ncVar[index] this_height = height_ncVar[index] this_alt = alt_ncVar[index] time = self.times[index] # Masked array via conditional, don't color the land unless it has water on it masked_data = np.ma.masked_where(this_height == 0.0000, this_level) print("step: {} time: {}".format(index, time)) # Plot the surface for this time step if surface is None: ax.imshow(masked_data, cmap=cmap, origin='lower', norm=norm, extent=[ self.minlon, self.maxlon, self.minlat, self.maxlat ], interpolation='none') else: surface.set_data(masked_data) # Text box with the time plt.figtext(0.02, 0.5, 'Time: {:02d}:{:02d}'.format( int(time / 60), int(time % 60)), bbox={ 'facecolor': 'yellow', 'pad': 5 }) writer.grab_frame()
def render_heatmap(data: pd.DataFrame, ax_hm: plt.Axes = None, cmap: colors.Colormap = None, norm: colors.Normalize = colors.Normalize(), annotate: bool = True, annotation_valfmt: str = '{x:.0f}', add_sep_colorbar: bool = False, ax_cb: plt.Axes = None, colorbar_label: str = None, use_index_labels: bool = False, xlabel: str = None, ylabel: str = None, fig_canvas_title: str = None, fig_size: tuple = (8, 6), manipulate_ticks: bool = False, tick_label_prec: int = 3, xtick_label_prec: int = None, ytick_label_prec: int = None) -> (plt.Figure, plt.Figure): """ Plot a 2D heat map from a 2D `pandas.DataFrame` using pyplot. The data frame should have exactly one column index level and one row index level. These will automatically become the axis ticks. It is assumed that the data is equally spaced. .. note:: If you want to have a tight layout, it is best to pass axes of a figure with `tight_layout=True` or `constrained_layout=True`. :param data: 2D pandas DataFrame :param ax_hm: axis to draw the heat map onto, if `None` a new figure is created :param cmap: colormap passed to imshow :param norm: colormap normalizer passed to imshow :param annotate: select if the heat map should be annotated :param annotation_valfmt: format of the annotations inside the heat map, irrelevant if annotate = False :param add_sep_colorbar: flag if a separate color bar is added automatically :param ax_cb: axis to draw the color bar onto, if `None` a new figure is created :param colorbar_label: label for the color bar :param use_index_labels: flag if index names from the pandas DataFrame are used as labels for the x- and y-axis. This can can be overridden by xlabel and ylabel. :param xlabel: label for the x axis :param ylabel: label for the y axis :param fig_canvas_title: window title for the heat map plot, no title by default :param fig_size: width and height of the figure in inches :param manipulate_ticks: apply custom manipulation to the x and y axis ticks :param tick_label_prec: floating point precision of the x- and y-axis labels. This can be overwritten xtick_label_prec and ytick_label_prec :param xtick_label_prec: floating point precision of the x-axis labels :param ytick_label_prec: floating point precision of the y-axis labels :return: handles to the heat map and the color bar figures (None if not existent) """ if isinstance(data, pd.DataFrame): if not isinstance(data.index, NumericIndex): raise pyrado.TypeErr(given=data.index, expected_type=NumericIndex) if not isinstance(data.columns, NumericIndex): raise pyrado.TypeErr(given=data.columns, expected_type=NumericIndex) # Extract the data x = data.columns y = data.index else: raise pyrado.TypeErr(given=data, expected_type=pd.DataFrame) # Create axes if not provided if ax_hm is None: fig_hm, ax_hm = plt.subplots(1, figsize=fig_size) else: fig_hm = ax_hm.figure if fig_canvas_title is not None: fig_hm.canvas.set_window_title(fig_canvas_title) # Create the image img = ax_hm.imshow(data, cmap=cmap, norm=norm, aspect=(x.max() - x.min()) / (y.max() - y.min()), origin='lower', extent=[x.min(), x.max(), y.min(), y.max()]) # former: aspect='auto' # Set axes limits ax_hm.set_xlim(x.min(), x.max()) ax_hm.set_ylim(y.min(), y.max()) # Annotate the heat map if annotate: _annotate_heatmap(img, valfmt=annotation_valfmt) # Prepare the ticks if manipulate_ticks: _setup_index_axis( ax_hm.xaxis, x, use_index_labels, xtick_label_prec if xtick_label_prec is not None else tick_label_prec) _setup_index_axis( ax_hm.yaxis, y, use_index_labels, ytick_label_prec if ytick_label_prec is not None else tick_label_prec) ax_hm.stale = True # to cause redraw # Set the labels if xlabel is not None: ax_hm.set_xlabel(xlabel) if ylabel is not None: ax_hm.set_ylabel(ylabel) # Add color bar if requested if add_sep_colorbar: # Draw a new figure and re-plot the color bar there if ax_cb is None: fig_cb, ax_cb = plt.subplots(1, figsize=fig_size) else: fig_cb = plt.gcf() if colorbar_label is not None: colorbar.ColorbarBase(ax_cb, cmap=cmap, norm=norm, label=colorbar_label) else: colorbar.ColorbarBase(ax_cb, cmap=cmap, norm=norm) # if colorbar_label is not None: # fig_cb.colorbar(img, ax=ax_cb, label=colorbar_label) # plt.colorbar works, too # else: # fig_cb.colorbar(img, ax=ax_cb) # plt.colorbar works, too # # # Only show the color bar # ax_cb.remove() return fig_hm, fig_cb else: return fig_hm, None
def bathy_topo_map(LLD_FILE): save_file = os.path.splitext(LLD_FILE)[0] + '_bathymap.png' extension = os.path.splitext(LLD_FILE)[1] # Read bathymetry/topography data if extension == ".txt": data = np.genfromtxt(LLD_FILE, dtype=[('lat', 'f8'), ('lon', 'f8'), ('z', 'f8')], skip_header=6) # Reshape into matrices Ncols = len(np.unique(data['lon'])) Nrows = len(np.unique(data['lat'])) X = data['lon'].reshape(Nrows, Ncols) Y = data['lat'].reshape(Nrows, Ncols) Z = data['z'].reshape(Nrows, Ncols) # Data ranges lon_min, lon_max = data['lon'].min(), data['lon'].max() lat_min, lat_max = data['lat'].min(), data['lat'].max() elif extension == ".nc": data = Dataset(LLD_FILE, 'r') # Reshape into matrices Ncols = len(data['longitude'][:]) Nrows = len(data['latitude'][:]) X, Y = np.meshgrid(data['longitude'][:], data['latitude'][:]) Z = data['altitude'][::] # Data ranges lon_min, lon_max = data['longitude'][:].min( ), data['longitude'][:].max() lat_min, lat_max = data['latitude'][:].min(), data['latitude'][:].max() else: raise BaseException("Bathymetry file is an unsupported file type") mean_lat = 0.5 * (lat_min + lat_max) mean_lon = 0.5 * (lon_min + lon_max) lon_range = lon_max - lon_min lat_range = lat_max - lat_min cmap = plt.get_cmap('terrain') interp = 'nearest' framelabelfont = mfont.FontProperties(family='Arial', style='normal', variant='normal', size=14) # catch any nan values masked_data = np.ma.masked_invalid(Z) cmap.set_bad('red') # Color limits z_min, z_max = masked_data.min(), masked_data.max() z_lim = max(np.abs(z_min), np.abs(z_max)) norm = mcolor.Normalize(vmin=-z_lim, vmax=z_lim) # Initialize the frame and axes fig = plt.figure() m = Basemap(projection='cyl', llcrnrlat=lat_min, urcrnrlat=lat_max, llcrnrlon=lon_min, urcrnrlon=lon_max, lat_0=mean_lat, lon_0=mean_lon, resolution='h') m.ax = fig.add_subplot(111) m.drawmeridians(np.linspace(lon_min, lon_max, num=5.0), labels=[0, 0, 0, 1], linewidth=0) m.drawparallels(np.linspace(lat_min, lat_max, num=5.0), labels=[1, 0, 0, 0], linewidth=0) m.drawcoastlines(linewidth=0.5) # Colorbar divider = make_axes_locatable(m.ax) cbar_ax = divider.append_axes("right", size="5%", pad=0.05) plt.figtext(0.96, 0.7, r'elevation $[m]$', rotation='vertical', fontproperties=framelabelfont) cb = mcolorbar.ColorbarBase(cbar_ax, cmap=cmap, norm=norm) # Plot the contours #m.contourf(X, Y, masked_data, 100, cmap=cmap, norm=norm, extend='both', zorder=1) m.ax.imshow(masked_data, cmap=cmap, origin='lower', norm=norm, extent=[lon_min, lon_max, lat_min, lat_max], interpolation=interp) plt.savefig(save_file, dpi=100) print("Saved to " + save_file)
ax1.imshow(im_rectif, extent=extents) for i in range(0, len(gcpXYreproj)): r = np.floor(resids[i]) if r > 10: ci = 10 else: ci = int(r) ax1.plot(gcpXYreproj[i][1] - camLoc[0], gcpXYreproj[i][2] - camLoc[1], 'o', markeredgecolor='k', markerfacecolor=clist[ci]) cb1 = colorbar.ColorbarBase(cbax, cmap=cm, boundaries=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], ticks=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], spacing='proportional', orientation='horizontal', label='Reprojection residual (m)', ticklocation='top') ax1.set_xlabel('Relative Easting (m)', fontsize=8) ax1.set_ylabel('Relative Northing (m)', fontsize=8) ax1.set_xticks([100, 150, 200, 250, 300, 350]) ax1.set_yticks([-50, -100, -150, -200]) ax3.boxplot(resids, sym='kx') ax3.set_xticks([]) ax3.set_ylim(0, 11) ax3.set_xlim(0.85, 1.15) ax3.set_yticks([0, 5, 10]) ax3.set_xlabel('Residuals', fontsize=6) ax4.plot(abs(difs[:, 0]), abs(difs[:, 1]), '.', markersize=2) ax4.plot(np.linspace(0, 10, 20), np.linspace(0, 10, 20), 'k-')
# Figure Mapping fig=plt.figure() plt.bar(pos,data['mean'],width=1, color=cmap.to_rgba(colors,alpha=0.75),linewidth=2,yerr=data['SE']*1.96, error_kw=dict(ecolor='black', lw=2, capsize=20, capthick=2),picker=10) plt.xticks(pos, data.index.values, alpha=0.8) plt.ylim(0,55000) plt.tick_params(top='off', bottom='off', labelbottom='on') plt.axhline(y=Reference,color='grey',lw=3) plt.title('You Have Choosen as a Reference Line {:5.0f} Votes \n Click Inside the Graph to Change the Reference'.format(round(Reference,0))) plt.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.2) # BarLegend ax1 = fig.add_axes([0.1, 0.1, 0.8, 0.05]) cb = colorbar.ColorbarBase(ax1,cmap='RdBu_r', norm=col.Normalize(0,1), orientation='horizontal', ticks=[0.1,0.9]) cb.set_ticklabels(['Low Probability \n Above Reference','High Probability \n Above Reference']) plt.show() # Define oneclick to update plot via new choosen reference def onclick(event): plt.clf() Reference=event.ydata # Update Colors: colors = [] for Lower,Upper in zip(data['LowerCI'],data['UpperCI']): if Lower>Reference: colors.append(1) else: