def plot_peak_altitude(self, ax=None, true_color='k', apparent_color='grey'): if ax is None: ax = plt.gca() plt.sca(ax) for d in self.digitization_list: if d.is_invertible(): if d.altitude.size == 0: try: d.invert(substitute_fp=ais_code.ne_to_fp(4.)) except BaseException as e: print(e) continue if apparent_color: plt.plot(d.time, d.altitude[-1], marker='.', ms=self.marker_size, color=apparent_color) alt = mex.iau_pgr_alt_lat_lon_position(float(d.time))[0] plt.plot(d.time, alt - d.traced_delay[-1] * ais_code.speed_of_light_kms / 2., marker='.', color=true_color, ms=self.marker_size) celsius.ylabel(r'$h_{max} / km$') plt.ylim(0o1, 249)
def plot_r(self, ax=None, label=True, fmt='k-', **kwargs): if ax is None: ax = plt.gca() plt.sca(ax) self.generate_position() plt.plot(self.t, self.iau_pos[0] / mex.mars_mean_radius_km, fmt, **kwargs) celsius.ylabel(r'$r / R_M$')
def plot_timeseries(self, ax=None, vmin=None, vmax=None, colorbar=False, label=True): if vmin is None: vmin = self.vmin if vmax is None: vmax = self.vmax if ax is None: ax = plt.gca() plt.sca(ax) plt.cla() plt.imshow(self.tser_arr[::-1,:], vmin=vmin, vmax=vmax, interpolation='Nearest', extent=self.extent, origin='upper',aspect='auto') plt.xlim(self.extent[0], self.extent[1]) plt.ylim(self.extent[2], self.extent[3]) # plt.vlines(self.ionogram_list[0].time, self.extent[2], self.extent[3], 'r') if label: celsius.ylabel('f / MHz') if colorbar: old_ax = plt.gca() plt.colorbar( cax = celsius.make_colorbar_cax(), ticks=self.cbar_ticks ).set_label(r"$Log_{10} V^2 m^{-2} Hz^{-1}$") plt.sca(old_ax)
def plot_matches_group(g,how='chi',ntop=8): """ Plot matches from h5 group Pulls out the relavent arrays from a group and runs plot_matches Parameters ---------- g : h5 group containing the following datasets - arr : DataSet with spectra - smres : DataSet with specmatch results """ smres = pd.DataFrame(g['smres'][:]) smres = results.smres_add_chi(smres) lspec = g['lspec'][:] smres.index = np.arange(len(smres)) if how=='chi': smresbest = smres.sort_values(by='chi') elif how=='close': targname = smio.kbc_query(smres.targobs[0])['name'] tpar = dict(lib.ix[targname]) smres['close'] = close(tpar,smres) smresbest = smres.sort_values(by='close') smresbest = smresbest.iloc[:ntop] plot_matches(smresbest,lspec) plt.sca(plt.gcf().get_axes()[0])
def orbit_plots(orbit_list=[8020, 8021, 8022, 8023, 8024, 8025], resolution=200, ax=None): if ax is None: ax = plt.gca() plt.sca(ax) orbits = {} props = dict(marker="None", hold=True, mec=None, linestyle="-", markeredgewidth=0.0) # props = dict(marker='o', hold=True,mec='None',line style='None',markeredgewidth=0.0) for orbit in orbit_list: orbit_t = mex.orbits[orbit] print(orbit, orbit_t.start, orbit_t.finish) t = np.linspace(orbit_t.start, orbit_t.finish, resolution) pos = mex.iau_pgr_alt_lat_lon_position(t) # orbits[orbit] = dict(lat = np.rad2deg(pos[2]), lon = np.rad2deg(np.unwrap(pos[1])), # alt=pos[0] - mex.mars_mean_radius_km, t=t) orbits[orbit] = dict(lat=pos[1], lon=np.rad2deg(np.unwrap(np.deg2rad(pos[2]))), alt=pos[0], t=t) ll = plt.plot(orbits[orbit]["lon"], orbits[orbit]["lat"], label=str(orbit), **props) plt.plot( orbits[orbit]["lon"] + 360.0, orbits[orbit]["lat"], label="_nolegend_", color=ll[0].get_color(), **props ) plt.plot( orbits[orbit]["lon"] - 360.0, orbits[orbit]["lat"], label="_nolegend_", color=ll[0].get_color(), **props ) plt.xlim(-180, 180) plt.ylim(-90, 90) plt.xlabel("Longitude / deg") plt.ylabel("Latitude / deg") plt.legend(loc="center left", bbox_to_anchor=(1.01, 0.5), numpoints=1, title="Orbit") ax.xaxis.set_major_locator(celsius.CircularLocator()) ax.yaxis.set_major_locator(celsius.CircularLocator())
def plot_acf_ccf(axacf,axccf,wlo,whi): b = (w > wlo) & (w < whi) plt.sca(axccf) dvmax = plot_ccf(w[b], tspec[b], mspec[b]) plt.sca(axacf) thwhm,mhwhm = plot_acf(w[b], tspec[b], mspec[b]) return dvmax,thwhm,mhwhm
def plot_altitude(self, ax=None, label=True, fmt='k-', **kwargs): if ax is None: ax = plt.gca() plt.sca(ax) self.generate_position() plt.plot(self.t, self.iau_pos[0] - mex.mars_mean_radius_km, fmt, **kwargs) if label: celsius.ylabel('h / km')
def setlims(d): plt.sca(d['ax']) xk = d['xk'] yk = d['yk'] if limd.keys().count(xk)==1: plt.xlim(*limd[xk]) if limd.keys().count(yk)==1: plt.ylim(*limd[yk])
def plot_sza(self, ax=None, label=True, fmt='k-', **kwargs): if ax is None: ax = plt.gca() plt.sca(ax) self.make_axis_circular(ax) self.generate_position() plt.plot(self.t, self.sza, fmt, **kwargs) if label: celsius.ylabel(r'$SZA / deg$') plt.ylim(0., 180.)
def plot_lat(self, ax=None, label=True, fmt='k-', **kwargs): if ax is None: ax = plt.gca() plt.sca(ax) self.make_axis_circular(ax) self.generate_position() plt.plot(self.t, self.iau_pos[1], fmt, **kwargs) if label: celsius.ylabel(r'$\lambda$') plt.ylim(-90., 90.)
def flipax(d): plt.sca(d['ax']) xk = d['xk'] yk = d['yk'] if flipd.keys().count(xk)==1: if flipd[xk]: flip('x') if flipd.keys().count(yk)==1: if flipd[yk]: flip('y')
def plot_mod_b(self, fmt='k.', ax=None, field_model=True, errors=True, field_color='blue', br=True, t_offset=0., label=True, **kwargs): if ax is None: ax = plt.gca() plt.sca(ax) sub = [d for d in self.digitization_list if np.isfinite(d.td_cyclotron)] if len(sub) == 0: print("No digitizations with marked cyclotron frequency lines") return t = np.array([d.time for d in sub]) b = np.array([d.td_cyclotron for d in sub]) e = np.array([d.td_cyclotron_error for d in sub]) # print b # print e b, e = ais_code.td_to_modb(b, e) b *= 1.E9 e *= 1.E9 if errors: for tt,bb,ee in zip(t,b,e): plt.plot((tt,tt),(bb+ee,bb-ee), color='lightgrey',linestyle='solid',marker='None') plt.plot(tt,bb,fmt,ms=self.marker_size, **kwargs) # plt.errorbar(t, b, e, fmt=fmt, ms=self.marker_size, **kwargs) else: plt.plot(t, b, fmt, ms=self.marker_size, **kwargs) if field_model: self.generate_position() if field_color is None: field_color = fmt[0] # b = self.quick_field_model(self.t) self._computed_field_model = self.field_model(self.iau_pos) bmag = np.sqrt(np.sum(self._computed_field_model**2., 0)) plt.plot(self.t - t_offset, bmag, color=field_color, ls='-') if br: plt.plot(self.t - t_offset, self._computed_field_model[0], 'r-') plt.plot(self.t - t_offset, -1. * self._computed_field_model[0], 'r', ls='dashed') model_at_value = np.interp(t, self.t, bmag) inx = (model_at_value > 100.) & ((b / model_at_value) < 0.75) plt.plot(t[inx], b[inx], 'ro', mec='r', mfc='none', ms=5., mew=1.2) if label: celsius.ylabel(r'$\mathrm{|B|/nT}$') plt.ylim(0., 200)
def velocityshift(wav, flux, ref_wav, ref_flux, plot=False): """ Find the velocity shift between two spectra. Args: wav (array): Wavelength array. flux (array): Continuum-normalized spectrum. ref_wav (array): ref_flux (array): Returns: vmax (float): Velocity of the cross-correlation peak. Positive velocity means that observed spectrum is red-shifted with respect to the reference spectrum. corrmax (float): Peak cross-correlation amplitude. """ nwav = flux.size # Build spline object for resampling the model spectrum ref_spline = InterpolatedUnivariateSpline(ref_wav, ref_flux) # Convert target and model spectra to constant log-lambda scale wav, flux, dvel = loglambda(wav, flux) ref_flux = ref_spline(wav) # Perform cross-correlation, and use quadratic interpolation to # find the velocity value that maximizes the cross-correlation # amplitude. If `lag` is negative, the observed spectrum need to # be blue-shifted in order to line up with the observed # spectrum. Thus, to put the spectra on the same scale, the # observed spectrum must be red-shifted, i.e. vmax is positive. flux-=np.mean(flux) ref_flux-=np.mean(ref_flux) lag = np.arange(-nwav + 1, nwav) dvel = -1.0 * lag * dvel corr = np.correlate(ref_flux, flux, mode='full') vmax, corrmax = quadratic_max(dvel, corr) if plot: from matplotlib import pylab as plt fig,axL = plt.subplots(ncols=2) plt.sca(axL[0]) plt.plot(wav,ref_flux) plt.plot(wav,flux) plt.sca(axL[1]) vrange = (-100,100) b = (dvel > vrange[0]) & (dvel < vrange[1]) plt.plot(dvel[b],corr[b]) plt.plot([vmax],[corrmax],'o',label='Cross-correlation Peak') fig.set_tight_layout(True) plt.draw() plt.show() return vmax, corrmax
def test_axes_stuff(): fig = DJAPage(ratios=[2.,1., 0.63]) plt.sca(fig.top_axes) x = np.arange(360.) y = np.sin(x * np.pi/180. + 2.) plt.plot(x, y, 'r-') plt.sca(fig.bottom_axes) mb = add_labelled_bar(x,x) fig.register_new_axis(mb) plt.xlim(0., 360.) plt.show()
def plotline(x): ax = x['ax'] xk = x['xk'] plt.sca(ax) trans = blended_transform_factory(ax.transData,ax.transAxes) plt.axvline(smpar[xk],ls='--') plt.text(smpar[xk],0.9,'SM',transform=trans) if libpar is not None: plt.axvline(libpar[xk]) plt.text(libpar[xk],0.9,'LIB',transform=trans)
def wrapped_f(*args): for ax in axL: plt.sca(ax) f(*args) xl = plt.xlim() start = xl[0] step = (xl[1]-xl[0]) / float(nax) for ax in axL: plt.sca(ax) plt.xlim(start,start+step) start+=step
def plot_aspera_els(self, ax=None, **kwargs): if self.verbose: print('PLOT_ASPERA_ELS:') if ax is None: ax = plt.gca() else: plt.sca(ax) try: mex.aspera.plot_els_spectra(self.extent[0], self.extent[1], ax=ax, verbose=self.verbose, **kwargs) except Exception as e: print(e)
def plot_profiles(self, ax=None, vmin=4., vmax=5.5, cmap=None, cmticks=None, log=True, substitute_fp=None, **kwargs): """ Inverts the profiles, plots them versus time and altitude, color coded to density Does not show the 'first step' between the S/C plasma density and the first reflection """ if ax is None: ax = plt.gca() plt.sca(ax) ax.set_axis_bgcolor("gray") if cmap is None: cmap = matplotlib.cm.hot if cmticks is None: cmticks = [3, 4, 5, 6] n_profiles = int((self.extent[1] - self.extent[0]) / ais_code.ais_spacing_seconds) + 1 ranges = np.arange(80., 350., 1.) times = np.arange(self.extent[0], self.extent[1], ais_code.ais_spacing_seconds) img = np.zeros((len(times), len(ranges))) + np.nan label = r'$n_e$ / cm$^{-3}$' if log: f = np.log10 label = r'log ' + label else: f = lambda x: x if substitute_fp is None: subf = lambda t: 0. else: if hasattr(substitute_fp, '__call__'): subf = lambda t: substitute_fp(t) else: subf = lambda t: substitute_fp for i, d in enumerate(self.digitization_list): if d.is_invertible(): d.invert(substitute_fp=subf(d.time)) if d.altitude.size: ii = round((float(d.time) - times[0]) / ais_code.ais_spacing_seconds) img[ii,:] = np.interp(ranges, d.altitude[-1:0:-1], f(d.density[-1:0:-1]), right=np.nan, left=np.nan)[::-1] extent = (self.extent[0], self.extent[1], np.nanmin(ranges), np.nanmax(ranges)) plt.imshow(img.T, interpolation='Nearest', extent=extent, origin='upper',aspect='auto', vmin=vmin, vmax=vmax, cmap=cmap) celsius.ylabel("alt / km") old_ax = plt.gca() plt.colorbar(cax = celsius.make_colorbar_cax(), ticks=cmticks, **kwargs).set_label(label) plt.sca(old_ax)
def plot_frequency_altitude(self, f=2.0, ax=None, median_filter=False, vmin=None, vmax=None, altitude_range=(-99.9, 399.9), colorbar=False, return_image=False, annotate=True): if vmin is None: vmin = self.vmin if vmax is None: vmax = self.vmax if ax is None: ax = plt.gca() plt.sca(ax) plt.cla() freq_extent = (self.extent[0], self.extent[1], altitude_range[1], altitude_range[0]) i = self.ionogram_list[0] inx = 1.0E6* (i.frequencies.shape[0] * f) / (i.frequencies[-1] - i.frequencies[0]) img = self.tser_arr_all[:,int(inx),:] new_altitudes = np.arange(altitude_range[0], altitude_range[1], 14.) new_img = np.zeros((new_altitudes.shape[0], img.shape[1])) + np.nan for i in self.ionogram_list: e = int( round((i.time - self.extent[0]) / ais_code.ais_spacing_seconds )) pos = mex.iau_r_lat_lon_position(float(i.time)) altitudes = pos[0] - ais_code.speed_of_light_kms * ais_code.ais_delays * 0.5 - mex.mars_mean_radius_km s = np.argsort(altitudes) new_img[:, e] = np.interp(new_altitudes, altitudes[s], img[s,e], left=np.nan, right=np.nan) plt.imshow(new_img, vmin=vmin, vmax=vmax, interpolation='Nearest', extent=freq_extent, origin='upper', aspect='auto') plt.xlim(freq_extent[0], freq_extent[1]) plt.ylim(*altitude_range) ax.set_xlim(self.extent[0], self.extent[1]) ax.xaxis.set_major_locator(celsius.SpiceetLocator()) celsius.ylabel(r'Alt./km') if annotate: plt.annotate('f = %.1f MHz' % f, (0.02, 0.9), xycoords='axes fraction', color='cyan', verticalalignment='top', fontsize='small') if colorbar: old_ax = plt.gca() plt.colorbar(cax = celsius.make_colorbar_cax(), ticks=self.cbar_ticks).set_label(r"$Log_{10} V^2 m^{-2} Hz^{-1}$") plt.sca(old_ax) if return_image: return new_img, freq_extent, new_altitudes
def plot_lon(self, ax=None, label=True, fmt='k-', **kwargs): if ax is None: ax = plt.gca() plt.sca(ax) self.make_axis_circular(ax) self.generate_position() v = celsius.deg_unwrap(self.iau_pos[2]) for i in [-1,0,1]: plt.plot(self.t, v + i * 360, fmt, **kwargs) if label: celsius.ylabel(r'$\varphi$') plt.ylim(0., 360.)
def plot_frame(dfplot,df,**kwargs): """ Plot DataFrame Helper function for panels. """ for i in dfplot.index: x = dfplot.ix[i] plt.sca(x['ax']) plt.plot(df[x['xk']],df[x['yk']],**kwargs) plt.xlabel(x['xL']) plt.ylabel(x['yL'])
def violin_plot(ax, values_list, measure_name, group_names, fontsize, color='blue', ttest=False): ''' This is a little wrapper around the statsmodels violinplot code so that it looks nice :) ''' # IMPORTS import matplotlib.pylab as plt import statsmodels.api as sm import numpy as np # Make your violin plot from the values_list # Don't show the box plot because it looks a mess to be honest # we're going to overlay a boxplot on top afterwards plt.sca(ax) # Adjust the font size font = { 'size' : fontsize} plt.rc('font', **font) max_value = np.max(np.concatenate(values_list)) min_value = np.min(np.concatenate(values_list)) vp = sm.graphics.violinplot(values_list, ax = ax, labels = group_names, show_boxplot=False, plot_opts = { 'violin_fc':color , 'cutoff': True, 'cutoff_val': max_value, 'cutoff_type': 'abs'}) # Now plot the boxplot on top bp = plt.boxplot(values_list, sym='x') for key in bp.keys(): plt.setp(bp[key], color='black', lw=fontsize/10) # Adjust the power limits so that you use scientific notation on the y axis plt.ticklabel_format(style='sci', axis='y') ax.yaxis.major.formatter.set_powerlimits((-3,3)) plt.tick_params(axis='both', which='major', labelsize=fontsize) # Add the y label plt.ylabel(measure_name, fontsize=fontsize) # And now turn off the major ticks on the y-axis for t in ax.yaxis.get_major_ticks(): t.tick1On = False t.tick2On = False return ax
def plot_ne(self, fmt='k.', ax=None, errors=True, label=True, marsis=True, aspera=False, full_marsis=False, **kwargs): if ax is None: ax = plt.gca() plt.sca(ax) def parse_error(d): if not np.isfinite(d.fp_local): return f = ais_code.fp_to_ne(d.fp_local) f0 = ais_code.fp_to_ne(d.fp_local + d.fp_local_error) f1 = ais_code.fp_to_ne(d.fp_local - d.fp_local_error) if errors: plt.plot((d.time, d.time),(f0,f1), color='lightgrey', linestyle='solid', marker='None', zorder=-1000,**kwargs) plt.plot(d.time, f, fmt, ms=self.marker_size, zorder=1000, **kwargs) if full_marsis and hasattr(d, 'maximum_fp_local'): plt.plot(d.time, ais_code.fp_to_ne(d.maximum_fp_local), 'b.', ms=self.marker_size, zorder=900, **kwargs) if full_marsis: if np.isfinite(d.morphology_fp_local): v, e = ais_code.fp_to_ne(d.morphology_fp_local, d.morphology_fp_local_error) plt.errorbar(float(d.time), v, yerr=e, marker='x', ms=1.3, color='purple', zorder=1e90, capsize=0., ecolor='plum') if np.isfinite(d.integrated_fp_local): v, e = ais_code.fp_to_ne(d.integrated_fp_local, d.integrated_fp_local_error) plt.errorbar(float(d.time), v, yerr=e, marker='x', ms=1.3, color='blue', zorder=1e99, capsize=0., ecolor='cyan') # if hasattr(d, 'fp_local_length'): # if d.fp_local_length > 40.: # plt.scatter(d.time, f, s=(float(d.fp_local_length)/80. *)**2. * 5., color='k') # plt.errorbar(d.time, f, df, fmt='k', marker='None') list(map(parse_error, self.digitization_list)) print("FP_LOCAL: %d" % len( [d for d in self.digitization_list if np.isfinite(d.fp_local)])) ax.set_yscale('log') plt.ylim(11., 1.1E5) if label: # celsius.ylabel(r'$\mathrm{n_e / cm^{-3}}$') plt.ylabel(r'n$_e$ / cm$^{-3}$')
def plotres(d): plt.sca(d['ax']) x = smpar[d['xk']] y = smpar[d['yk']] tkw = dict(ha='center',va='center') plt.plot([x],[y],'oc',ms=15,mew=0) plt.text(x,y,'SM',**tkw) if libpar is not None: x = libpar[d['xk']] y = libpar[d['yk']] plt.plot([x],[y],'oc',ms=15,mew=0) plt.text(x,y,'LIB',**tkw)
def plot_ground_deltat(self, ax=None): if ax is None: ax = plt.gca() plt.sca(ax) t = [d.time for d in self.digitization_list if np.isfinite(d.ground)] d = [d.ground for d in self.digitization_list if np.isfinite(d.ground)] dnew = [] for time, delay in zip(t, d): mex_pos = mex.iau_mars_position(float(time)) alt = np.sqrt(np.sum(mex_pos * mex_pos)) - mex.mars_mean_radius_km dnew.append( (delay - alt * 2. / ais_code.speed_of_light_kms) * 1.0E3) plt.plot(t, dnew) celsius.ylabel(r'$\Delta\tau_D$ / ms')
def chisq(df, fig=None, columns=['teff','logg','fe'], **kwargs): """Make a multi-panel plot of chisq """ ncols = len(columns) if fig is None: fig,axL = plt.subplots(ncols=ncols) else: axL = fig.get_axes() i = 0 for col in columns: plt.sca(axL[i]) plt.semilogy() plt.plot(df[col],df['chisq'],**kwargs) i+=1
def hcolorbar(*args, **kwargs): '''Arguments, label='', nticks=[3], cticks=[None], axes=[[0.8,0.01,0.1,0.02]] #[left,bottom, width,height], cax=[None] colorbar axis returns colorbar''' try: itemlabel = args[0].get_label() if itemlabel.startswith('_'): itemlabel = '' except: itemlabel = '' label = kwargs.pop('label', itemlabel) nticks = kwargs.pop('nticks', 3) cticks = kwargs.pop('cticks', None) cticknames = kwargs.pop('cticknames', None) rotate = kwargs.pop('rotate', None) tickfmt = kwargs.pop('tickfmt', None) axes = kwargs.pop('axes', [0.8,0.01,0.1,0.02]) ax = pylab.gca() tmp = dict( # cax = pylab.axes(axes), orientation='horizontal', ) tmp.update(kwargs) if 'cax' not in tmp: tmp['cax'] = pylab.axes(axes) cb = pylab.colorbar(*args, **tmp) cb.set_label(label) if cticks is None: cticks = np.linspace(cb.vmin, cb.vmax, nticks) cb.set_ticks(cticks) if tickfmt is not None: tmp = map(tickfmt.format, cticks) cb.set_ticklabels(tmp) if cticknames is not None: cb.set_ticklabels(cticknames) if rotate is not None: pylab.setp(pylab.xticks(axes=cb.ax)[1], rotation=90, ha='center') pylab.sca(ax) return cb
def setup_lat_lon_ax(ax=None, label=True, tickspacing=30.0): if ax is None: ax = plt.gca() else: plt.sca(ax) plt.xlim(-180, 180) plt.xticks(np.arange(-360.0 - 180, 360.0 + 180 + 1.0, tickspacing)) plt.ylim(-90, 90) plt.yticks(np.arange(-90, 90 + 1.0, tickspacing)) if label: plt.xlabel("Lon. / deg") plt.ylabel("Lat. / deg") ax.set_aspect("equal")
def plot_frequency_range(self, f_min=0., f_max=0.2, ax=None, median=False, vmin=None, vmax=None, colorbar=False, max_value=False): if vmin is None: vmin = self.vmin if vmax is None: vmax = self.vmax if ax is None: ax = plt.gca() plt.sca(ax) plt.cla() freq_extent = (self.extent[0], self.extent[1], ais_code.ais_max_delay*1E3, ais_code.ais_min_delay*1E3) i = self.ionogram_list[0] inx, = np.where((i.frequencies > f_min*1E6) & (i.frequencies < f_max*1E6)) if inx.shape[0] < 2: raise ValueError("Only %d frequency bins selected." % inx.shape[0]) print("Averaging over %d frequency bins" % inx.shape[0]) if median: if inx.shape[0] < 3: raise ValueError("Median here only really makes sense for 3 or more bins") img = np.median(self.tser_arr_all[:,inx,:],1) elif max_value: img = np.max(self.tser_arr_all[:,inx,:],1) else: img = np.mean(self.tser_arr_all[:,inx,:],1) plt.imshow(img, vmin=vmin, vmax=vmax, interpolation='Nearest', extent=freq_extent, origin='upper',aspect='auto') plt.xlim(freq_extent[0], freq_extent[1]) plt.ylim(freq_extent[2], freq_extent[3]) # plt.vlines(i.time,freq_extent[2],freq_extent[3], 'r') celsius.ylabel(r'$\tau_D / ms$' '\n' '%.1f-%.1f MHz' % (f_min, f_max)) # plt.annotate('f = %.1f - %.1f MHz' % (f_min, f_max), (0.02, 0.9), xycoords='axes fraction', # color='grey', verticalalignment='top', fontsize='small') if colorbar: old_ax = plt.gca() plt.colorbar(cax = celsius.make_colorbar_cax(), ticks=self.cbar_ticks).set_label(r"$Log_{10} V^2 m^{-2} Hz^{-1}$") plt.sca(old_ax)
def make_colorbar_cax(ax=None, width=0.01, offset=0.02, height=0.9, left=False, half=False, upper=True): """Define a new vertical colorbar axis relative to :ax:. Avoids 'stealing' space from the axis, required for stack plots. Args: ax: Axes instance to work with, defaults to current. width: width of colorbar relative to axes width height: height relative to axes height offset: offset relative to appropriate axes dimension left: place on left side (default False) half: only occupy half the vertical extent, for two colorbars? upper: upper of two colorbars? Returns: new axes instance for passing to colorbar(cax=...) """ if ax is None: ax = plt.gca() else: plt.sca(ax) bbox = ax.get_position() x0 = bbox.x1 if left: offset = abs(offset) * -1.0 x0 = bbox.x0 y0 = bbox.y0 y1 = bbox.y1 # ys = (1.0 - height) * (y1 - y0) ys = (1.0 - height) * (y1 - y0) / 2. # new_ax_coords = [x0 + offset, y0 + ys, width, height * (y1 - y0) - ys] new_ax_coords = [x0 + offset, y0 + ys, width, height * (y1 - y0)] # |==|---------|==|----------|==| if half: new_ax_coords[3] = new_ax_coords[3] / 2. if upper: new_ax_coords[1] = y0 + height * (y1 - y0) * 0.5 + ys/2. else: new_ax_coords[1] -= ys/2. new_ax = ax.figure.add_axes(new_ax_coords) plt.sca(ax) return new_ax
y_sel = (z >= elev_min) & (z < elev_max) & (x_sel) else: y_sel = (z >= elev_min) & (x_sel) sel_nodes = np.where(y_sel)[0] H[i, j] = int(len(sel_nodes)) #sel_nodes = grid.core_nodes if len(sel_nodes) > 0: cat[sel_nodes] = val cat_bin[sel_nodes] = len(sel_nodes) cat_plot[sel_nodes] = cat[sel_nodes] val += 1 cat_plot[cat_plot == 0] = cat_plot[cat_plot > 0].min() - 1 plt.sca(axarr[i]) imshow_grid(grid, cat_plot, cmap='viridis') plt.axis('off') plt.savefig(site + '.cats.png') plt.figure(figsize=(4, 3), dpi=300) imshow_grid(grid, cat, cmap='tab20', limits=(0.5, 20.5)) #, plot_name='Chi-Elevation Category') plt.axis('off') plt.savefig(site + '.all_cats.png') plt.figure(dpi=300) imshow_grid(grid, cat_bin, cmap='inferno',
statement = statement.replace('AW', str(np.around(aw, 2))) statement = statement.replace('WA', str(np.around(wa, 2))) statement = statement.replace('AA', str(np.around(aa, 2))) print(statement) cmap = sns.diverging_palette(220, 10, as_cmap=True) names = [ 'white_m', 'api_m', 'hispanic_m', 'black_m', 'white_w', 'api_w', 'hispanic_w', 'black_w' ] plt.close() sns.set(style='white', font=font) fig, axes = plt.subplots(ncols=2, nrows=1, figsize=(7.5, 4)) axes = axes.flatten() plt.sca(axes[0]) heat = sns.heatmap(np.around((citation_matrix / citation_matrix.sum()) * 100, 2), annot=True, ax=axes[0], annot_kws={"size": 8}, cmap=cmap, vmax=1, vmin=0) axes[0].set_ylabel('first author', labelpad=0) heat.set_yticklabels(names, rotation=0) axes[0].set_xlabel('last author', labelpad=1) heat.set_xticklabels(names, rotation=90) heat.set_title('percentage of citations') citation_matrix_sum = citation_matrix / np.sum(citation_matrix)
def train_model(network): adam = Adam(lr=learning_rate, beta_1=0.9, beta_2=0.999, epsilon=1e-08) network.compile(loss='categorical_crossentropy', optimizer=adam, metrics=['accuracy']) network.summary() plot_model(network, to_file=graph_path) batch_num = 0 model_save_acc = 0 all_train_accuracy = [] all_train_loss = [] all_tst_accuracy = [] tst_data = DataGenerator(h5file_path=tst_path, batch_size=batch_size, frames=frames) tst_data_name = tst_data.get_data_name() tst_cursors = [tst_data.get_cursors(name) for name in tst_data_name] for epoch in range(epochs): accuracy_list = [] loss_list = [] print(epoch + 1, ' epoch is beginning......') train_data = DataGenerator(h5file_path=train_path, batch_size=batch_size, frames=frames) train_data_name = train_data.get_data_name() train_data_cursors = train_data.batch_cursors(len(train_data_name)) index_num = random.sample(range(len(train_data_cursors)), len(train_data_cursors)) for ind in index_num: batch_num += 1 up_data_0, down_data_0, train_labels_0 \ = train_data.generate_batch_data(train_data_name, train_data_cursors[ind], 0) up_data_1, down_data_1, train_labels_1 \ = train_data.generate_batch_data(train_data_name, train_data_cursors[ind], 1) train_loss = network.train_on_batch( [up_data_0, up_data_1, down_data_0, down_data_1], train_labels_0) accuracy_list.append(train_loss[1]) loss_list.append(train_loss[0]) if batch_num % 50 == 0: print('the %r batch: loss: %r accuracy: %r' % (batch_num, train_loss[0], train_loss[1])) epoch_accuracy = sum(accuracy_list) / len(accuracy_list) epoch_loss = sum(loss_list) / len(loss_list) all_train_accuracy.append(epoch_accuracy) all_train_loss.append(epoch_loss) print('the %r epoch: mean loss: %r mean accuracy: %r' % (epoch + 1, epoch_loss, epoch_accuracy)) if epoch >= 0: tst_accuracy_list = [] for num in range(len(tst_data_name)): tst_up_0, tst_down_0, tst_labels_0 = \ tst_data.get_tst_single_data(tst_data_name[num], tst_cursors[num], 0) tst_up_1, tst_down_1, tst_labels_1 = \ tst_data.get_tst_single_data(tst_data_name[num], tst_cursors[num], 1) tst_loss = network.test_on_batch( [tst_up_0, tst_up_1, tst_down_0, tst_down_1], tst_labels_0) tst_accuracy_list.append(tst_loss[1]) tst_accuracy = sum(tst_accuracy_list) / len(tst_accuracy_list) all_tst_accuracy.append(tst_accuracy) print('The test data accuracy: %r' % tst_accuracy) if tst_accuracy > model_save_acc: network.save_weights(weight_path) model_save_acc = tst_accuracy pl.figure() trn_acc = pl.subplot(2, 2, 1) trn_loss = pl.subplot(2, 2, 2) tst_acc = pl.subplot(2, 1, 2) pl.sca(trn_acc) pl.plot(range(len(all_train_accuracy)), all_train_accuracy, label='train accuracy') pl.xlabel('Epoch') pl.ylabel('Accuracy') pl.ylim(0, 1.0) pl.sca(trn_loss) pl.plot(range(len(all_train_loss)), all_train_loss, label='loss') pl.xlabel('Epoch') pl.ylabel('Loss') pl.ylim(0, 5.0) pl.sca(tst_acc) pl.plot(range(len(all_tst_accuracy)), all_tst_accuracy, label='test accuracy') pl.xlabel('Epoch') pl.ylabel('Accuracy') pl.ylim(0, 1.0) pl.legend() pl.show()
self.c.canopy.flux_to(self.c.evaporation, t), self.c.surfacewater.flux_to(self.c.evaporation, t), self.c.layers[0].flux_to(self.c.evaporation, t), self.c.layers[0].flux_to(self.c.transpiration, t), self.c.surfacewater.flux_to(self.c.layers[0], t), )) resistance.append((self.et.RAA, self.et.RAC, self.et.RAS, self.et.RSC, self.et.RSS)) mpot.append(self.c.surface_water_coverage()) return vol, flux, resistance, mpot if __name__ == '__main__': print(cmf.__version__) m = Model() vol, flux, resistance, mpot = m(10) from matplotlib import pylab as plt fig, ax = plt.subplots(3, 1, sharex='all') plt.sca(ax[0]) plt.plot(vol) plt.legend(['Canopy', 'Surfacewater', 'Layer'], loc=0) plt.sca(ax[1]) plt.plot(flux) plt.legend( ['E_Canopy', 'E_Surfacewater', 'E_Layer', 'T_Layer', 'Infiltration'], loc=0) plt.sca(ax[2]) plt.plot(resistance) plt.legend('RAA RAC RAS RSC RSS'.split(), loc=0) plt.show()
frl3NonVoida = (np.shape(np.where(np.abs(l3_nonVoid) <= i)[0])[0] / (1. * size_fact**3)) * L frl1NonVoid = np.append(frl1NonVoid, frl1NonVoida) frl2NonVoid = np.append(frl2NonVoid, frl2NonVoida) frl3NonVoid = np.append(frl3NonVoid, frl3NonVoida) #f, axarr = plt.subplots(2, sharex=True) #axarr[0].plot(x, y) #axarr[0].set_title('Sharing X axis') #axarr[1].scatter(x, y) #plt.figure(5) f, axarr = plt.subplots(2, figsize=(8, 12), sharex=True) f.subplots_adjust(hspace=0.02) plt.sca(axarr[0]) axarr[0].plot(cutfr, frl1, '--', lw=1.5, label=r"$\lambda_1$") axarr[0].plot(cutfr, frl2, '--', lw=1.5, label=r"$\lambda_2$") axarr[0].plot(cutfr, frl3, '--', lw=1.5, label=r"$\lambda_3$") plt.xscale('log') #plt.xlim(np.min(cutfr), 4) #plt.ylim(9,95) #plt.yticks( [0.1, 0.5, 0.9] ) axarr[0].legend(loc="upper left") plt.ylabel(" Volume fraction of $|\lambda| < \lambda_{th}$ ") plt.minorticks_on() #plt.xlabel(r" $ \lambda_{th} $") #plt.subplot(2,1,2) plt.sca(axarr[1])