def plot_band(x, y, yerr=None, ymin=None, ymax=None, alpha=0.25, **keywords): """Plots a shaded region to represent the uncertainty in time series data.""" if 'alpha' not in keywords: keywords['alpha']=0.25 if ymin is not None and ymax is not None: x0,y0 = p.poly_between(x,ymin,ymax) else: if yerr==None: yerr = 0.05*y x0,y0 = p.poly_between(x,y-y_err,y+y_err) p.fill(x0,y0,**keywords) return
def plot_spectrum(self, filename, width=0.2, xlim=None): """ Make pretty plot of the linear response. Parameters: =========== filename: output file name (&format, supported by matplotlib) width: width of Lorenzian broadening xlim: energy range for plotting tuple (emin,emax) """ import pylab as pl if not self.done: self.run() e, f = mix.broaden(self.omega * Hartree, self.F, width=width, N=1000, extend=True) f = f / max(abs(f)) pl.plot(e, f, lw=2) xs, ys = pl.poly_between(e, 0, f) pl.fill(xs, ys, fc="b", ec="b", alpha=0.5) pl.ylim(0, 1.2) if xlim == None: pl.xlim(0, self.emax * Hartree * 1.2) else: pl.xlim(xlim) pl.xlabel("energy (eV)") pl.ylabel("linear optical response") pl.title("Optical response") pl.savefig(filename) # pl.show() pl.close()
def plot_spectrum(self, filename, width=0.2, xlim=None): """ Make pretty plot of the linear response. Parameters: =========== filename: output file name (&format, supported by matplotlib) width: width of Lorenzian broadening xlim: energy range for plotting tuple (emin,emax) """ import pylab as pl if not self.done: self.run() e, f = mix.broaden(self.omega * Hartree, self.F, width=width, N=1000, extend=True) f = f / max(abs(f)) pl.plot(e, f, lw=2) xs, ys = pl.poly_between(e, 0, f) pl.fill(xs, ys, fc='b', ec='b', alpha=0.5) pl.ylim(0, 1.2) if xlim == None: pl.xlim(0, self.emax * Hartree * 1.2) else: pl.xlim(xlim) pl.xlabel('energy (eV)') pl.ylabel('linear optical response') pl.title('Optical response') pl.savefig(filename) #pl.show() pl.close()
def my_hist(ax, l, interval, max_r, color="g", marker=".", fill=False, kde=False): if not l: return n, p = [], [] total_len = len(l) for i in np.arange(0, max_r, interval): xmin, xmax = i - 0.5 * interval, i + 0.5 * interval nx = [x for x in l if xmin <= x < xmax] n.append(i) p.append(len(nx) * 100.0 / total_len) if kde: from scipy import stats kernel = stats.gaussian_kde(l) n = np.arange(0, max_r, interval) kn = kernel(n) p = kn / sum(kn) * 100 if fill: from pylab import poly_between xs, ys = poly_between(n, 0, p) line = ax.fill(xs, ys, fc=color, alpha=0.5) else: line = ax.plot( n, p, color=color, lw=2, ms=3, marker=marker, mfc="w", mec=color, mew=2 ) return line
def standardize_interval(lower, upper, mean, SD, ax=None, data=True, units='Units', standardized=False, include_mean=False, fontsize=15, **fill_opts): from pylab import poly_between if ax is None: fig = plt.gcf() ax = fig.add_subplot(111) xf, yf = poly_between([lower, mean, upper], [-0.05, -0.05, -0.05], [0.05, 0.05, 0.05]) ax.fill(xf, yf, hatch='/', alpha=0.5, **fill_opts) ax.set_ylim([-0.4, 0.3]) ax.set_xlim([lower - 0.55 * SD, upper + 0.3 * SD]) ax.set_xticks([lower, upper]) ax.set_yticks([]) ax.set_xticklabels(['', '']) ax.text(lower - 0.4 * SD, -0.2, units + ':', fontsize=fontsize) ax.text(lower, -0.3, lower, fontsize=fontsize, horizontalalignment='left') ax.text(upper, -0.3, upper, fontsize=fontsize, horizontalalignment='right') include_mean = include_mean or standardized if include_mean: ax.plot([mean, mean], [-0.1, 0.1], 'k--', linewidth=4) if standardized: ax.set_ylim([-0.6, 0.3]) ax.text(lower - 0.5 * SD, -0.4, 'Standardized:', color='red', fontsize=fontsize) ax.text(lower, -0.5, '(%0.1f-%0.1f)/%0.1f=%0.2f' % (lower, mean, SD, (lower - mean) / SD), fontsize=fontsize, horizontalalignment='left', color='red') ax.text(upper, -0.5, '(%0.1f-%0.1f)/%0.1f=%0.2f' % (upper, mean, SD, (upper - mean) / SD), fontsize=fontsize, horizontalalignment='right', color='red') if data: ax.set_title('Mean=%0.1f, SD=%0.1f' % (mean, SD), fontsize=20) else: ax.set_title('Mean=%0.1f, SE=%0.1f' % (mean, SD), fontsize=20) return ax
def my_hist(ax, l, interval, max_r, color='g', marker='.', fill=False): if not l: return n, p = [], [] total_len = len(l) for i in np.arange(0, max_r, interval): xmin, xmax = i - .5 * interval, i + .5 * interval nx = [x for x in l if xmin <= x < xmax] n.append(i) p.append(len(nx) * 100. / total_len) if fill: from pylab import poly_between xs, ys = poly_between(n, 0, p) line = ax.fill(xs, ys, fc=color, alpha=.5) else: line = ax.plot(n, p, color=color, lw=2, ms=3, marker=marker, mfc="w", mec=color, mew=2) return line
def contourf(self, direction, var, **kwargs): """ Plot a windrose in filled mode. For each var bins, a line will be draw on the axes, a segment between each sector (center to center). Each line can be formated (color, width, ...) like with standard plot pylab command. Mandatory: * direction : 1D array - directions the wind blows from, North centred * var : 1D array - values of the variable to compute. Typically the wind speeds Optional: * nsector: integer - number of sectors used to compute the windrose table. If not set, nsectors=16, then each sector will be 360/16=22.5°, and the resulting computed table will be aligned with the cardinals points. * bins : 1D array or integer- number of bins, or a sequence of bins variable. If not set, bins=6, then bins=linspace(min(var), max(var), 6) * blowto : bool. If True, the windrose will be pi rotated, to show where the wind blow to (usefull for pollutant rose). * colors : string or tuple - one string color ('k' or 'black'), in this case all bins will be plotted in this color; a tuple of matplotlib color args (string, float, rgb, etc), different levels will be plotted in different colors in the order specified. * cmap : a cm Colormap instance from matplotlib.cm. - if cmap == None and colors == None, a default Colormap is used. others kwargs : see help(pylab.plot) """ bins, nbins, nsector, colors, angles, kwargs = self._init_plot( direction, var, **kwargs) kwargs.pop('facecolor', None) kwargs.pop('edgecolor', None) # closing lines angles = np.hstack((angles, angles[-1] - 2 * np.pi / nsector)) vals = np.hstack((self._info['table'], np.reshape(self._info['table'][:, 0], (self._info['table'].shape[0], 1)))) offset = 0 for i in range(nbins): val = vals[i, :] + offset offset += vals[i, :] zorder = ZBASE + nbins - i xs, ys = poly_between(angles, 0, val) patch = self.fill(xs, ys, facecolor=colors[i], edgecolor=colors[i], zorder=zorder, **kwargs) self.patches_list.extend(patch)
def contourf(self, dir, var, **kwargs): """ Plot a windrose in filled mode. For each var bins, a line will be draw on the axes, a segment between each sector (center to center). Each line can be formated (color, width, ...) like with standard plot pylab command. Mandatory: * dir : 1D array - directions the wind blows from, North centred * var : 1D array - values of the variable to compute. Typically the wind speeds Optional: * nsector: integer - number of sectors used to compute the windrose table. If not set, nsectors=16, then each sector will be 360/16=22.5°, and the resulting computed table will be aligned with the cardinals points. * bins : 1D array or integer- number of bins, or a sequence of bins variable. If not set, bins=6, then >>> bins=linspace(min(var), max(var), 6) * blowto : bool. If True, the windrose will be pi rotated, to show where the wind blow to (usefull for pollutant rose). * colors : string or tuple - one string color ('k' or 'black'), in this case all bins will be plotted in this color; a tuple of matplotlib color args (string, float, rgb, etc), different levels will be plotted in different colors in the order specified. * cmap : a cm Colormap instance from matplotlib.cm. - if cmap == None and colors == None, a default Colormap is used. others kwargs : see help(pylab.plot) """ bins, nbins, nsector, colors, angles, kwargs = self._init_plot(dir, var, **kwargs) null = kwargs.pop('facecolor', None) null = kwargs.pop('edgecolor', None) #closing lines angles = np.hstack((angles, angles[-1]-2*np.pi/nsector)) vals = np.hstack((self._info['table'], np.reshape(self._info['table'][:,0], (self._info['table'].shape[0], 1)))) offset = 0 for i in range(nbins): val = vals[i,:] + offset offset += vals[i, :] zorder = ZBASE + nbins - i xs, ys = poly_between(angles, 0, val) patch = self.fill(xs, ys, facecolor=colors[i], edgecolor=colors[i], zorder=zorder, **kwargs) self.patches_list.extend(patch)
def draw(self): self.figure.clf() self.axes.scatter(self.M, self.D, c=self.marker_color, s=self.marker_size, edgecolor='gray') self.axes.set_xlabel("Mother's height (inches)", fontsize=15) self.axes.set_ylabel("Daughter's height (inches)", fontsize=15) if self.strip is not None: s = self.strip xf, yf = poly_between([s-.5,s+.5], [50,50], [75, 75]) self.axes.fill(xf, yf, facecolor=self.strip_color, alpha=0.4, hatch='/')
def standardize_left(point, mean, SD, ax=None, data=True, units='Units', standardized=False, include_mean=False, fontsize=15, **fill_opts): ''' Half-open interval to the right... ''' if ax is None: fig = plt.gcf() ax = fig.add_subplot(111) lower = min(point, mean - 2 * SD) upper = max(point, mean + 2 * SD) xf, yf = poly_between([mean - 1000 * SD, point], [-0.05, -0.05], [0.05, 0.05]) ax.fill(xf, yf, hatch='/', alpha=0.5, **fill_opts) ax.set_ylim([-0.4, 0.3]) ax.set_xlim([lower - 0.55 * SD, upper + 1.5 * SD]) ax.set_xticks([lower, upper]) ax.set_yticks([]) ax.set_xticklabels(['', '']) ax.text(lower - 0.4 * SD, -0.2, units + ':', fontsize=fontsize) ax.text(point, -0.3, point, fontsize=fontsize, horizontalalignment='left') if include_mean: ax.plot([mean, mean], [-0.1, 0.1], 'k--', linewidth=4) if standardized: ax.set_ylim([-0.6, 0.3]) ax.text(lower - 0.5 * SD, -0.4, 'Standardized:', color='red', fontsize=fontsize) ax.text(point, -0.5, '(%0.1f-%0.1f)/%0.1f=%0.2f' % (point, mean, SD, (point * 1. - mean) / SD), fontsize=fontsize, horizontalalignment='left', color='red') if data: ax.set_title('Mean=%0.1f, SD=%0.1f' % (mean, SD), fontsize=20) else: ax.set_title('Mean=%0.1f, SE=%0.1f' % (mean, SD), fontsize=20) return ax
def my_hist(ax, l, interval, max_r, color='g'): if not l: return from pylab import poly_between n, p = [], [] total_len = len(l) for i in np.arange(0, max_r, interval): xmin, xmax = i - .5 * interval, i + .5 * interval nx = [x for x in l if xmin <= x < xmax] n.append(i) p.append(len(nx) * 100. / total_len) xs, ys = poly_between(n, 0, p) return ax.fill(xs, ys, fc=color, alpha=.3)
def make_cumulative_plot(grid, values, width, weights_list, labels=None, colors=None): """ Make a cumulative plot from the values that are broadened with gaussian distributions of FWHM=width. The weights_list is an array of the shape [:,len(values)]. """ import pylab if labels == None: labels = ['_nolegend_' for i in range(len(weights_list))] if colors == None: colors = np.random.random((len(values), 4)) colors[:,3] = 1 low = np.zeros_like(grid) for weights, color, label in zip(weights_list, colors, labels): up = low + broaden(grid, values, width, weights) x, y = pylab.poly_between(grid, low, up) pylab.fill(x, y, facecolor=color, edgecolor='none', label=label) low = up
def standardize_interval(lower, upper, mean, SD, ax=None, data=True, units='Units', standardized=False, include_mean=False, fontsize=15, **fill_opts): from pylab import poly_between if ax is None: fig = plt.gcf() ax = fig.add_subplot(111) xf, yf = poly_between([lower,mean,upper],[-0.05,-0.05,-0.05],[0.05,0.05,0.05]) ax.fill(xf, yf, hatch='/', alpha=0.5, **fill_opts) ax.set_ylim([-0.4,0.3]) ax.set_xlim([lower-0.55*SD,upper+0.3*SD]) ax.set_xticks([lower,upper]) ax.set_yticks([]) ax.set_xticklabels(['','']) ax.text(lower - 0.4*SD, -0.2, units + ':', fontsize=fontsize) ax.text(lower, -0.3, lower, fontsize=fontsize, horizontalalignment='left') ax.text(upper, -0.3, upper, fontsize=fontsize, horizontalalignment='right') include_mean = include_mean or standardized if include_mean: ax.plot([mean, mean], [-0.1,0.1], 'k--', linewidth=4) if standardized: ax.set_ylim([-0.6,0.3]) ax.text(lower-0.5*SD, -0.4, 'Standardized:', color='red', fontsize=fontsize) ax.text(lower, -0.5, '(%0.1f-%0.1f)/%0.1f=%0.2f' % (lower, mean, SD, (lower-mean)/SD), fontsize=fontsize, horizontalalignment='left', color='red') ax.text(upper, -0.5, '(%0.1f-%0.1f)/%0.1f=%0.2f' % (upper, mean, SD, (upper-mean)/SD), fontsize=fontsize, horizontalalignment='right', color='red') if data: ax.set_title('Mean=%0.1f, SD=%0.1f' % (mean, SD), fontsize=20) else: ax.set_title('Mean=%0.1f, SE=%0.1f' % (mean, SD), fontsize=20) return ax
def draw(self): self.figure.clf() self.axes.scatter(self.M, self.D, c=self.marker_color, s=self.marker_size, edgecolor='gray') self.axes.set_xlabel("Mother's height (inches)", fontsize=15) self.axes.set_ylabel("Daughter's height (inches)", fontsize=15) if self.strip is not None: s = self.strip xf, yf = poly_between([s - .5, s + .5], [50, 50], [75, 75]) self.axes.fill(xf, yf, facecolor=self.strip_color, alpha=0.4, hatch='/')
def standardize_left(point, mean, SD, ax=None, data=True, units='Units', standardized=False, include_mean=False, fontsize=15, **fill_opts): ''' Half-open interval to the right... ''' if ax is None: fig = plt.gcf() ax = fig.add_subplot(111) lower = min(point, mean - 2*SD) upper = max(point, mean + 2*SD) xf, yf = poly_between([mean-1000*SD,point],[-0.05,-0.05],[0.05,0.05]) ax.fill(xf, yf, hatch='/', alpha=0.5, **fill_opts) ax.set_ylim([-0.4,0.3]) ax.set_xlim([lower-0.55*SD,upper+1.5*SD]) ax.set_xticks([lower,upper]) ax.set_yticks([]) ax.set_xticklabels(['','']) ax.text(lower - 0.4*SD, -0.2, units + ':', fontsize=fontsize) ax.text(point, -0.3, point, fontsize=fontsize, horizontalalignment='left') if include_mean: ax.plot([mean, mean], [-0.1,0.1], 'k--', linewidth=4) if standardized: ax.set_ylim([-0.6,0.3]) ax.text(lower-0.5*SD, -0.4, 'Standardized:', color='red', fontsize=fontsize) ax.text(point, -0.5, '(%0.1f-%0.1f)/%0.1f=%0.2f' % (point, mean, SD, (point*1.-mean)/SD), fontsize=fontsize, horizontalalignment='left', color='red') if data: ax.set_title('Mean=%0.1f, SD=%0.1f' % (mean, SD), fontsize=20) else: ax.set_title('Mean=%0.1f, SE=%0.1f' % (mean, SD), fontsize=20) return ax
def make_cumulative_plot(grid, values, width, weights_list, labels=None, colors=None): """ Make a cumulative plot from the values that are broadened with gaussian distributions of FWHM=width. The weights_list is an array of the shape [:,len(values)]. """ import pylab if labels == None: labels = ['_nolegend_' for i in range(len(weights_list))] if colors == None: colors = np.random.random((len(values), 4)) colors[:, 3] = 1 low = np.zeros_like(grid) for weights, color, label in zip(weights_list, colors, labels): up = low + broaden(grid, values, width, weights) x, y = pylab.poly_between(grid, low, up) pylab.fill(x, y, facecolor=color, edgecolor='none', label=label) low = up
def wavelet_plt(ts,c,**kwargs): fontsize=18 keys=kwargs.keys() if 'ax1_title' in keys: ax1_title=kwargs['ax1_title'] else: ax1_title=None if 'cbarnorm' in keys: cbarnorm = kwargs['cbarnorm'] else: cbarnorm = 2 if 'coi' in keys: coi = kwargs['coi'] else: coi = None if 'cs_threshold' in keys: cs_threshold = kwargs['cs_threshold'] else: cs_threshold = 0.4 if 'fname' in keys: fname = kwargs['fname'] mkplot = True else: fname = None mkplot=False if 'peak' in keys: peak = kwargs['peak'] else: peak = 0 if 'scales' in keys: scales = kwargs['scales'] if 'sampf' in keys: sampf = kwargs['sampf'] scales=scales/sampf else: scales = None if 'show_plot' in keys: show_plot = kwargs['show_plot'] else: show_plot = True if 'mask' in keys: mask = kwargs['mask'] else: mask = None if 'use_valid_gws' in keys: use_valid_gws=kwargs['use_valid_gws'] else: use_valid_gws=False if 'wdu' in keys: wdu=kwargs['wdu'] else: wdu=1 T=scales*wdu time = np.arange(0,c.shape[1]) gws = metobs.bl.turb.wavelets.get_gws(c,mask=None) if mkplot: fig = plt.figure(num=1,figsize=(16,12)) axt = fig.add_subplot(2,4,3) fig.clear() fig = plt.figure(num=1,figsize=(16,12)) ax1 = fig.add_subplot(2,1,1) ax1.clear() t=ax1.get_position() t2=axt.get_position() ax1pos=t.get_points() axtpos=t2.get_points() ax1pos[1][0]=axtpos[1][0]*0.95 t.set_points(ax1pos) ax1.set_position(t) #ax1.pcolormesh(time,T,c) ax1.imshow(c,aspect='auto',origin = 'bottom') if coi is not None: xs,ys = poly_between(np.arange(0,len(coi)),np.max(coi),coi) ax1.fill(xs,ys,'k',alpha=0.2) ax1.set_xlim(0,c.shape[1]) ax1.set_ylim(0,c.shape[0]) #ax2 = fig.add_subplot(2,5,5, sharey=ax1) ax2 = fig.add_subplot(2,5,5) ax2.semilogx(gws,T,'k+') if mask is not None: ax2.semilogx(metobs.bl.turb.wavelets.get_gws(c,mask=mask),T,'g+') ax2.legend(('all','valid')) else: ax2.legend(('all'),) ax2.grid(b=True,color='k',linestyle='-',linewidth=1) ax1.set_yticks(ax2.get_yticks()/(wdu)) ax1.set_yticklabels((ax1.get_yticks()*wdu).astype(int)) ax1.set_xticklabels((ax1.get_xticks()/sampf).astype(int)) ax1.set_xlim(0,c.shape[1]) ax1.set_ylim(0,c.shape[0]) ax1.set_ylabel('Period (s)',fontsize=fontsize) ax2.set_title('Global Wavelet Power Specturm') if ax1_title is not None: ax1.set_title(ax1_title,fontsize=fontsize) # norm = Normalize(-cbarnorm,cbarnorm) lpos = ax1.get_position() t = lpos.get_points() t[0][0] = t[1][0] t[1][0] = 1.02*t[1][0] lpos.set_points(t) cax = fig.add_axes(lpos) # cbar = matplotlib.colorbar.ColorbarBase(ax=cax, # norm=norm, orientation='vertical') cbar=ax1.figure.colorbar(ax1.images[0],cax=cax) cbar.set_label("T'") ax3 = fig.add_subplot(2,1,2, sharex=ax1) t = ax3.get_position() ax3pos=t.get_points() ax3pos[1][0]=ax1.get_position().get_points()[1][0] t.set_points(ax3pos) ax3.set_position(t) ax3.plot(ts,'k') ########################################################### # # Detect Coherent Structures # ########################################################### # find extreama in global wavelet spectrum if use_valid_gws: start,stop,gws_extrema = metobs.vis.wavelets.find_peaks(c,peak,cs_threshold,mask=mask) else: start,stop,gws_extrema = metobs.vis.wavelets.find_peaks(c,peak,cs_threshold) if start == 0: highlight_cs=False else: highlight_cs = True # Create and plot bins for shading x=[] y=[] xa=[] ya=[] if highlight_cs: for i in range(0,len(start)): x=np.arange(start[i],stop[i]) y=np.repeat(np.max(np.abs(ts)),len(x)) xa.append(x) ya.append(y) if mkplot: xs,ys=poly_between(x,-np.max(np.abs(ts)),y) ax3.fill(xs,ys,'k',alpha=0.2) else: xa=None ya=None if mkplot: ax3.set_ylim((np.min(ts),np.max(ts))) if highlight_cs: ax4=ax3.twinx() ax4.plot(c[gws_extrema[peak],:],'r',linewidth=3) ax4.legend(('peak scale: '+`np.int(gws_extrema[peak]*wdu)`+' s',)) ax4.set_xlim((0,c.shape[1])) ax4.set_xticklabels((ax4.get_xticks()/sampf).astype(int)) ax4.set_xlabel('time (s)',fontsize=fontsize) ax4.set_ylabel('Wavelet Coefficient\nalong GWPS Peak Scale',fontsize=fontsize) else: ax3.set_xlim((0,c.shape[1])) ax3.grid() ax3.set_ylabel('Temperature(detrended) (K)',fontsize=fontsize) if (fname is None) and (show_plot): plt.show() plt.clf() plt.close() elif (fname is not None): plt.savefig(fname,dpi=300) if show_plot is True: plt.show() plt.clf() plt.close() return(xa,ya),gws_extrema*wdu
def scalogram(self, show_coi=False, show_wps=False, ts=None, time=None, use_period=True, ylog_base=None, xlog_base=None, origin='top', figname=None): """ Scalogram plotting routine. Creates a simple scalogram, with optional wavelet power spectrum and time series plots of the transformed signal. Parameters ---------- show_coi : bool Set to True to see Cone of Influence show_wps : bool Set to True to see the Wavelet Power Spectrum ts : array 1D array containing time series data used in wavelet transform. If set, time series will be plotted. time : array of datetime objects 1D array containing time information use_period : bool Set to True to see figures use period instead of scale ylog_base : float If a log scale is desired, set `ylog_base` as float. (for log 10, set ylog_base = 10) xlog_base : float If a log scale is desired, set `xlog_base` as float. (for log 10, set xlog_base = 10) *note that this option is only valid for the wavelet power spectrum figure. origin : 'top' or 'bottom' Set origin of scale axis to top or bottom of figure Returns ------- None Examples -------- Create instance of SDG mother wavelet, normalized, using 10 scales and the center frequency of the Fourier transform as the characteristic frequency. Then, perform the continuous wavelet transform and plot the scalogram. # x = numpy.arange(0,2*numpy.pi,numpy.pi/8.) # data = numpy.sin(x**2) # scales = numpy.arange(10) # # mother_wavelet = SDG(len_signal = len(data), scales = np.arange(10), normalize = True, fc = 'center') # wavelet = cwt(data, mother_wavelet) # wave_coefs.scalogram(origin = 'bottom') """ import matplotlib.pyplot as plt import matplotlib.cm as cm from pylab import poly_between if ts is not None: show_ts = True else: show_ts = False if not show_wps and not show_ts: # only show scalogram figrow = 1 figcol = 1 elif show_wps and not show_ts: # show scalogram and wps figrow = 1 figcol = 4 elif not show_wps and show_ts: # show scalogram and ts figrow = 2 figcol = 1 else: # show scalogram, wps, and ts figrow = 2 figcol = 4 if time is None: x = np.arange(self.motherwavelet.len_signal) else: x = time if use_period: y = self.motherwavelet.scales / self.motherwavelet.fc else: y = self.motherwavelet.scales fig = plt.figure(figsize=(16, 12), dpi=160) ax1 = fig.add_subplot(figrow, figcol, 1) # if show wps, give 3/4 space to scalogram, 1/4 to wps if show_wps: # create temp axis at 3 or 4 col of row 1 axt = fig.add_subplot(figrow, figcol, 3) # get location of axtmp and ax1 axt_pos = axt.get_position() ax1_pos = ax1.get_position() axt_points = axt_pos.get_points() ax1_points = ax1_pos.get_points() # set axt_pos left bound to that of ax1 axt_points[0][0] = ax1_points[0][0] ax1.set_position(axt_pos) fig.delaxes(axt) if show_coi: # coi_coef is defined using the assumption that you are using # period, not scale, in plotting - this handles that behavior if use_period: coi = self.motherwavelet.get_coi( ) / self.motherwavelet.fc / self.motherwavelet.sampf else: coi = self.motherwavelet.get_coi() coi[coi == 0] = y.min() - 0.1 * y.min() xs, ys = poly_between(np.arange(0, len(coi)), np.max(y), coi) ax1.fill(xs, ys, 'k', alpha=0.4, zorder=2) contf = ax1.contourf(x, y, np.abs(self.coefs)**2) fig.colorbar(contf, ax=ax1, orientation='vertical', format='%2.1f') if ylog_base is not None: ax1.axes.set_yscale('log', basey=ylog_base) if origin is 'top': ax1.set_ylim((y[-1], y[0])) elif origin is 'bottom': ax1.set_ylim((y[0], y[-1])) else: raise OriginError('`origin` must be set to "top" or "bottom"') ax1.set_xlim((x[0], x[-1])) ax1.set_title('scalogram') ax1.set_ylabel('time') if use_period: ax1.set_ylabel('period') ax1.set_xlabel('time') else: ax1.set_ylabel('scales') if time is not None: ax1.set_xlabel('time') else: ax1.set_xlabel('sample') if show_wps: ax2 = fig.add_subplot(figrow, figcol, 4, sharey=ax1) if use_period: ax2.plot(self.get_wps(), y, 'k') else: ax2.plot(self.motherwavelet.fc * self.get_wps(), y, 'k') if ylog_base is not None: ax2.axes.set_yscale('log', basey=ylog_base) if xlog_base is not None: ax2.axes.set_xscale('log', basey=xlog_base) if origin is 'top': ax2.set_ylim((y[-1], y[0])) else: ax2.set_ylim((y[0], y[-1])) if use_period: ax2.set_ylabel('period') else: ax2.set_ylabel('scales') ax2.grid() ax2.set_title('wavelet power spectrum') if show_ts: ax3 = fig.add_subplot(figrow, 2, 3, sharex=ax1) ax3.plot(x, ts) ax3.set_xlim((x[0], x[-1])) ax3.legend(['time series']) ax3.grid() # align time series fig with scalogram fig t = ax3.get_position() ax3pos = t.get_points() ax3pos[1][0] = ax1.get_position().get_points()[1][0] t.set_points(ax3pos) ax3.set_position(t) if (time is not None) or use_period: ax3.set_xlabel('time') else: ax3.set_xlabel('sample') if figname is None: plt.show() else: plt.savefig(figname) plt.close('all')
def wavelet_plt(ts, c, **kwargs): fontsize = 18 keys = kwargs.keys() if 'ax1_title' in keys: ax1_title = kwargs['ax1_title'] else: ax1_title = None if 'cbarnorm' in keys: cbarnorm = kwargs['cbarnorm'] else: cbarnorm = 2 if 'coi' in keys: coi = kwargs['coi'] else: coi = None if 'cs_threshold' in keys: cs_threshold = kwargs['cs_threshold'] else: cs_threshold = 0.4 if 'fname' in keys: fname = kwargs['fname'] mkplot = True else: fname = None mkplot = False if 'peak' in keys: peak = kwargs['peak'] else: peak = 0 if 'scales' in keys: scales = kwargs['scales'] if 'sampf' in keys: sampf = kwargs['sampf'] scales = scales / sampf else: scales = None if 'sampf' in keys: sampf = kwargs['sampf'] else: sampf = 1 if 'show_plot' in keys: show_plot = kwargs['show_plot'] else: show_plot = True if 'mask' in keys: mask = kwargs['mask'] else: mask = None if 'use_valid_gws' in keys: use_valid_gws = kwargs['use_valid_gws'] else: use_valid_gws = False if 'wdu' in keys: wdu = kwargs['wdu'] else: wdu = 1 T = scales * wdu time = np.arange(0, c.shape[1]) gws = get_gws(c, mask=None) if mkplot: fig = plt.figure(num=1, figsize=(16, 12)) axt = fig.add_subplot(2, 4, 3) fig.clear() fig = plt.figure(num=1, figsize=(16, 12)) ax1 = fig.add_subplot(2, 1, 1) ax1.clear() t = ax1.get_position() t2 = axt.get_position() ax1pos = t.get_points() axtpos = t2.get_points() ax1pos[1][0] = axtpos[1][0] * 0.95 t.set_points(ax1pos) ax1.set_position(t) #ax1.pcolormesh(time,T,c) ax1.imshow(c, aspect='auto', origin='bottom') if coi is not None: xs, ys = poly_between(np.arange(0, len(coi)), np.max(coi), coi) ax1.fill(xs, ys, 'k', alpha=0.2) ax1.set_xlim(0, c.shape[1]) ax1.set_ylim(0, c.shape[0]) #ax2 = fig.add_subplot(2,5,5, sharey=ax1) ax2 = fig.add_subplot(2, 5, 5) ax2.semilogx(gws, T, 'k+') if mask is not None: ax2.semilogx(get_gws(c, mask=mask), T, 'g+') ax2.legend(('all', 'valid')) #else: # ax2.legend(('all'),) ax2.grid(b=True, color='k', linestyle='-', linewidth=1) ax1.set_yticks(ax2.get_yticks()) ax1.set_yticklabels((ax1.get_yticks()).astype(int)) ax1.set_xticklabels((ax1.get_xticks() / sampf).astype(int)) ax1.set_xlim(0, c.shape[1]) ax1.set_ylim(0, c.shape[0]) ax1.set_ylabel('Period (s)', fontsize=fontsize) ax2.set_title('Global Wavelet Power Specturm') if ax1_title is not None: ax1.set_title(ax1_title, fontsize=fontsize) # norm = Normalize(-cbarnorm,cbarnorm) lpos = ax1.get_position() t = lpos.get_points() t[0][0] = t[1][0] t[1][0] = 1.02 * t[1][0] lpos.set_points(t) cax = fig.add_axes(lpos) # cbar = matplotlib.colorbar.ColorbarBase(ax=cax, # norm=norm, orientation='vertical') cbar = ax1.figure.colorbar(ax1.images[0], cax=cax) cbar.set_label("T'") ax3 = fig.add_subplot(2, 1, 2, sharex=ax1) t = ax3.get_position() ax3pos = t.get_points() ax3pos[1][0] = ax1.get_position().get_points()[1][0] t.set_points(ax3pos) ax3.set_position(t) ax3.plot(ts, 'k') ########################################################### # # Detect Coherent Structures # ########################################################### # find extreama in global wavelet spectrum if use_valid_gws: start, stop, gws_extrema = metpy.vis.wavelets.find_peaks(c, peak, cs_threshold, mask=mask) else: start, stop, gws_extrema = metpy.vis.wavelets.find_peaks( c, peak, cs_threshold) if start == 0: highlight_cs = False else: highlight_cs = True # Create and plot bins for shading x = [] y = [] xa = [] ya = [] if highlight_cs: for i in range(0, len(start)): x = np.arange(start[i], stop[i]) y = np.repeat(np.max(np.abs(ts)), len(x)) xa.append(x) ya.append(y) if mkplot: xs, ys = poly_between(x, -np.max(np.abs(ts)), y) ax3.fill(xs, ys, 'k', alpha=0.2) else: xa = None ya = None if mkplot: ax3.set_ylim((np.min(ts), np.max(ts))) if highlight_cs: ax4 = ax3.twinx() ax4.plot(c[gws_extrema[peak], :], 'r', linewidth=3) ax4.legend(('peak scale: ' + ` np.int(gws_extrema[peak] * wdu) ` + ' s', )) ax4.set_xlim((0, c.shape[1])) ax4.set_xticklabels((ax4.get_xticks() / sampf).astype(int)) ax4.set_xlabel('time (s)', fontsize=fontsize) ax4.set_ylabel('Wavelet Coefficient\nalong GWPS Peak Scale', fontsize=fontsize) else: ax3.set_xlim((0, c.shape[1])) ax3.grid() ax3.set_ylabel('Temperature(detrended) (K)', fontsize=fontsize) if (fname is None) and (show_plot): plt.show() plt.clf() plt.close() elif (fname is not None): plt.savefig(fname, dpi=300) if show_plot is True: plt.show() plt.clf() plt.close() return (xa, ya), gws_extrema
print>>o, t, python, fortran, c o.close() fig = pl.figure() ax = fig.add_subplot(111) # plot the line info t0=1223991504.5 data=mix.read(datafile) timetuples = [localtime(sec) for sec in data[:,0]] dates = [datetime.date(a[0],a[1],a[2]) for a in timetuples] #data[:,0]-=t0 #data[:,0]/=356*24*3600 #pl.plot(dates,data[:,1]) #xs, ys = pl.poly_between(data[:,0],0,data[:,1]) xs, ys = pl.poly_between(dates,0,data[:,1]) pl.fill(xs,ys,label='python') xs, ys = pl.poly_between(dates,data[:,1],data[:,1]+data[:,2]) pl.fill(xs,ys,label='fortran') xs, ys = pl.poly_between(dates,data[:,1]+data[:,2],data[:,1]+data[:,2]+data[:,3]) pl.fill(xs,ys,label='C') pl.title('lines of code in hotbit') pl.xlabel('Years since 14.10 2008') pl.ylabel('Lines of code') pl.legend(loc=2) from matplotlib.dates import MonthLocator, WeekdayLocator, DateFormatter from matplotlib.dates import MONDAY mondays = WeekdayLocator(MONDAY) months = MonthLocator() monthsFmt = DateFormatter('%b %y')
def scalogram(self, show_coi=False, show_wps=False, ts=None, time=None, use_period=True, ylog_base=None, xlog_base=None, origin='top', figname=None): """ Scalogram plotting routine. Creates a simple scalogram, with optional wavelet power spectrum and time series plots of the transformed signal. Parameters ---------- show_coi : bool Set to True to see Cone of Influence show_wps : bool Set to True to see the Wavelet Power Spectrum ts : array 1D array containing time series data used in wavelet transform. If set, time series will be plotted. time : array of datetime objects 1D array containing time information use_period : bool Set to True to see figures use period instead of scale ylog_base : float If a log scale is desired, set `ylog_base` as float. (for log 10, set ylog_base = 10) xlog_base : float If a log scale is desired, set `xlog_base` as float. (for log 10, set xlog_base = 10) *note that this option is only valid for the wavelet power spectrum figure. origin : 'top' or 'bottom' Set origin of scale axis to top or bottom of figure Returns ------- None Examples -------- Create instance of SDG mother wavelet, normalized, using 10 scales and the center frequency of the Fourier transform as the characteristic frequency. Then, perform the continuous wavelet transform and plot the scalogram. # x = numpy.arange(0,2*numpy.pi,numpy.pi/8.) # data = numpy.sin(x**2) # scales = numpy.arange(10) # # mother_wavelet = SDG(len_signal = len(data), scales = np.arange(10), normalize = True, fc = 'center') # wavelet = cwt(data, mother_wavelet) # wave_coefs.scalogram(origin = 'bottom') """ import matplotlib.pyplot as plt import matplotlib.cm as cm from pylab import poly_between if ts is not None: show_ts = True else: show_ts = False if not show_wps and not show_ts: # only show scalogram figrow = 1 figcol = 1 elif show_wps and not show_ts: # show scalogram and wps figrow = 1 figcol = 4 elif not show_wps and show_ts: # show scalogram and ts figrow = 2 figcol = 1 else: # show scalogram, wps, and ts figrow = 2 figcol = 4 if time is None: x = np.arange(self.motherwavelet.len_signal) else: x = time if use_period: y = self.motherwavelet.scales / self.motherwavelet.fc else: y = self.motherwavelet.scales fig = plt.figure(figsize=(16, 12), dpi=160) ax1 = fig.add_subplot(figrow, figcol, 1) # if show wps, give 3/4 space to scalogram, 1/4 to wps if show_wps: # create temp axis at 3 or 4 col of row 1 axt = fig.add_subplot(figrow, figcol, 3) # get location of axtmp and ax1 axt_pos = axt.get_position() ax1_pos = ax1.get_position() axt_points = axt_pos.get_points() ax1_points = ax1_pos.get_points() # set axt_pos left bound to that of ax1 axt_points[0][0] = ax1_points[0][0] ax1.set_position(axt_pos) fig.delaxes(axt) if show_coi: # coi_coef is defined using the assumption that you are using # period, not scale, in plotting - this handles that behavior if use_period: coi = self.motherwavelet.get_coi() / self.motherwavelet.fc / self.motherwavelet.sampf else: coi = self.motherwavelet.get_coi() coi[coi == 0] = y.min() - 0.1 * y.min() xs, ys = poly_between(np.arange(0, len(coi)), np.max(y), coi) ax1.fill(xs, ys, 'k', alpha=0.4, zorder = 2) contf=ax1.contourf(x,y,np.abs(self.coefs)**2) fig.colorbar(contf, ax=ax1, orientation='vertical', format='%2.1f') if ylog_base is not None: ax1.axes.set_yscale('log', basey=ylog_base) if origin is 'top': ax1.set_ylim((y[-1], y[0])) elif origin is 'bottom': ax1.set_ylim((y[0], y[-1])) else: raise OriginError('`origin` must be set to "top" or "bottom"') ax1.set_xlim((x[0], x[-1])) ax1.set_title('scalogram') ax1.set_ylabel('time') if use_period: ax1.set_ylabel('period') ax1.set_xlabel('time') else: ax1.set_ylabel('scales') if time is not None: ax1.set_xlabel('time') else: ax1.set_xlabel('sample') if show_wps: ax2 = fig.add_subplot(figrow,figcol,4,sharey=ax1) if use_period: ax2.plot(self.get_wps(), y, 'k') else: ax2.plot(self.motherwavelet.fc * self.get_wps(), y, 'k') if ylog_base is not None: ax2.axes.set_yscale('log', basey=ylog_base) if xlog_base is not None: ax2.axes.set_xscale('log', basey=xlog_base) if origin is 'top': ax2.set_ylim((y[-1], y[0])) else: ax2.set_ylim((y[0], y[-1])) if use_period: ax2.set_ylabel('period') else: ax2.set_ylabel('scales') ax2.grid() ax2.set_title('wavelet power spectrum') if show_ts: ax3 = fig.add_subplot(figrow, 2, 3, sharex=ax1) ax3.plot(x, ts) ax3.set_xlim((x[0], x[-1])) ax3.legend(['time series']) ax3.grid() # align time series fig with scalogram fig t = ax3.get_position() ax3pos=t.get_points() ax3pos[1][0]=ax1.get_position().get_points()[1][0] t.set_points(ax3pos) ax3.set_position(t) if (time is not None) or use_period: ax3.set_xlabel('time') else: ax3.set_xlabel('sample') if figname is None: plt.show() else: plt.savefig(figname) plt.close('all')