def thetaeq(self, filled=True, cmap=None, **kwargs): self.initialize_plot() self.level = kwargs['level']*100 clevels = kwargs['clevels'] t_arrays = read_files(self, 'temperature') # [C] q_arrays = read_files(self, 'sphum') # [kg/kg] rh_arrays = read_files(self, 'relhumid') press = np.zeros(rh_arrays[0].shape)+kwargs['level'] # [hPa] X, Y = np.meshgrid(self.lons, self.lats) self.series['thetaeq'] = [] for i in range(len(self.dates)): mixr = thermo.mixing_ratio(specific_humidity=q_arrays[i]) theta = thermo.theta_equiv2(C=t_arrays[i], hPa=press, mixing_ratio=mixr, relh=rh_arrays[i]) val = get_value_at(-123., 38.5, theta, self) # closest to BBY self.series['thetaeq'].append(val) if filled: cf = self.axes[i].contourf(X, Y, theta, clevels, cmap=cmap) try: self.axes[i].cax.colorbar(cf, ticks=clevels[::4]) except AttributeError: add_colorbar(self.axes[i], cf) else: cs = self.axes[i].contour(X, Y, theta, clevels, colors='r', linewidths=0.6) clabels = self.axes[i].clabel(cs, clevels[::5], fontweight='bold', fontsize=10, fmt='%1.0f') [txt.set_color('r') for txt in clabels] set_limits(self, i) self.add_date(i) txt = 'Equivalent Potential Temperature [K] at {} hPa\n' self.title += txt.format(str(self.level/100))
def plot_vertical_shear(ax=None, wind=None, time=None, height=None): diff = np.diff(wind, axis=0) nrows, ncols = diff.shape # cmap = custom_cmap(17) # norm = colors.BoundaryNorm(np.arange(-20, 20), cmap.N) img = ax.imshow( diff, interpolation='nearest', origin='lower', # cmap=cmap, cmap='RdBu', vmin=-20, vmax=20, # norm=norm, extent=[0, ncols, 0, nrows], aspect='auto') add_colorbar(img, ax) format_xaxis(ax, time) format_yaxis(ax, height) ax.invert_xaxis() plt.draw()
for n, f in enumerate(fs): T, Tc, Hgt, timestamp = mf.parse_rass(f) if n == 0: Tstack = T Hgtstack = Hgt ts = np.array(timestamp) else: Tstack = np.hstack((Tstack, T)) Hgtstack = np.hstack((Hgtstack, Hgt)) ts = np.hstack((ts, np.array(timestamp))) thetav = get_thetav(case=r, Tv_array=Tstack, hgt_array=Hgtstack, homedir=homedir) titletxt = 'Case{} ({})' fig, ax = plt.subplots(2, 1, sharex=True) im = ax[0].imshow(Tstack, interpolation='none', origin='lower') ax[0].set_title(titletxt.format(str(r), ts[0].strftime('%Y-%b'))) ax[0].text(0.05, 0.9, 'Virtual temperature', transform=ax[0].transAxes) add_colorbar(ax[0], im) format_xaxis(ax[0], ts) format_yaxis(ax[0], Hgt[:, 0]) im = ax[1].imshow(thetav, vmin=282, vmax=294, interpolation='none', origin='lower') add_colorbar(ax[1], im) format_yaxis(ax[1], Hgt[:, 0]) ax[1].text(0.05, 0.9, 'Thetav', transform=ax[1].transAxes) ax[1].invert_xaxis() plt.tight_layout() plt.show(block=False)
def plot_shaded_map(ax=None, cmap='gist_earth',saveto=None): if ax is None: scale = 0.7 fig,ax = plt.subplots(figsize=(10*scale,10*scale)) # dtmfile = '/home/raul/Github/RadarQC/merged_dem_38-39_123-124_extended.tif' # dtmfile = '/home/raul/Dropbox/NOCAL_DEM/merged_dem_38-39_123-124_extended.tif' dtmfile = '/Users/raulvalenzuela/Dropbox/NOCAL_DEM/merged_dem_38-39_123-124_extended.tif' domain = [-123.4, -122.8, 38.8, 38.1, 8] elev = elevation(file_name=dtmfile, domain=domain) elev.get_elevation() elev_lims = [0,700] ls = LightSource(azdeg=15, altdeg=60) rgb = ls.shade(elev.dtm, cmap=getattr(plt.cm,cmap), vmin=elev_lims[0], vmax=elev_lims[1], blend_mode='soft', fraction=0.7) ax.imshow(rgb) " interpolate latlon to cartesian coords" nrows, ncols = elev.dtm.shape flat = interp1d(np.linspace(domain[3],domain[2],nrows), range(nrows)) flon = interp1d(np.linspace(domain[0], domain[1], ncols), range(ncols)) lat, lon = locations['FRS'] ax.scatter(flon(lon), flat(lat), color='r',s=50) lat, lon = locations['BBY'] ax.scatter(flon(lon), flat(lat), color='r',s=50) lat, lon = locations['CZD'] ax.scatter(flon(lon), flat(lat), color='r',s=50) 'Use a proxy artist for the colorbar' im = ax.imshow(elev.dtm, cmap=cmap, vmin=elev_lims[0], vmax=elev_lims[1], origin='lower', ) im.remove() add_colorbar(ax,im,label='Meters') ax.set_xticklabels('') ax.set_yticklabels('') plt.tight_layout() if saveto is not None: fname = 'shaded_terrain.png' plt.savefig(saveto + fname, dpi=300, format='png', papertype='letter', bbox_inches='tight')
def plot_elevation_map(self, ax=None, shaded=True, cmap=None, add_loc=None, colorbar=True, blend_mode='overlay', grid=True, gridcolor='w', altitude_range=[-10,600], contour_lines=None, latdelta=None, londelta=None, homed=None, figsize=None, addrivers=False, add_geoline=None): import os if homed is None: homed = os.path.expanduser('~') ' get elevation model ' if self.source is not None: fname = self.source dtmfile = homed + '/' + fname self.file_name = dtmfile if self.dtm is None: self.get_dem_matfile() else: fname = 'merged_dem_38-39_123-124_extended.tif' dtmfile = homed + '/Github/RadarQC/' + fname self.file_name = dtmfile if self.dtm is None: self.get_elevation() if ax is None: if figsize is None: fig,ax = plt.subplots(figsize=(10,10)) else: fig,ax = plt.subplots(figsize=figsize) ' make map axis ' m = Basemap(projection='merc', llcrnrlat=self.latn, urcrnrlat=self.latx, llcrnrlon=self.lonn, urcrnrlon=self.lonx, resolution='h', ax=ax) vmin, vmax = altitude_range if shaded: ' make hill shaded image ' ls = LightSource(azdeg=15, altdeg=60) rgb = ls.shade(self.dtm, cmap=getattr(plt.cm,cmap), vmin=vmin, vmax=vmax, blend_mode='soft', fraction=0.7) m.imshow(rgb) else: m.imshow(self.dtm, cmap=cmap, vmin=vmin, vmax=vmax) ' add parallels and meridians ' parallels = np.arange(-90, 90, latdelta) meridians = np.arange(-180, 180, londelta) lw = 0 if grid: lw = 1. parallels = m.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=10, labelstyle='+/-', fmt='%2.1f',linewidth=lw, color=gridcolor) m.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=10, labelstyle='+/-', fmt='%2.1f', linewidth=lw, color=gridcolor) for p in parallels: try: parallels[p][1][0].set_rotation(90) except: pass ' add locations ' if add_loc: fsize = 15 psize = 50 ec = (1.0,0,0,1) fc = (0.5,0,0,1) if isinstance(add_loc,dict): for loc, coord in locations.iteritems(): x, y = m(*coord[::-1]) m.scatter(x, y, psize, color='r') ax.text(x, y, loc, ha='right', va='bottom', color='r',fontsize=fsize,weight='bold') elif isinstance(add_loc,list): for loc in add_loc: coord = locations[loc] x, y = m(*coord[::-1]) m.scatter(x, y, psize, facecolor=fc,edgecolor=ec) ax.text(x, y, loc, ha='right', va='bottom', color='r',fontsize=fsize,weight='bold') ' add section line ' if add_geoline: if isinstance(add_geoline,dict): geolines = list(add_geoline) elif isinstance(add_geoline,list): geolines = add_geoline for line in geolines: x, y = get_line_ini_end(line) self.line_x = x self.line_y = y x, y = m(*[x, y]) if 'color' in line: color = line['color'] else: color='k' m.plot(x, y, color=color, linewidth=2) if 'ndiv' in line: ndiv = line['ndiv'] xp = np.linspace(x[0], x[1], ndiv) yp = np.linspace(y[0], y[1], ndiv) m.plot(xp, yp, marker='s', markersize=5, color=color) if 'label' in line: if 'center' in line: x,y = m(*line['center'][::-1]) ax.text(x,y,line['label']+r'$^\circ$', color=color, weight='bold', fontsize=15, rotation=90-line['az']) ' add rivers ' if addrivers: rivers = get_rivers(mmap=m) ax.add_collection(rivers) ' add colorbar ' if colorbar: im = m.imshow(self.dtm, cmap=cmap, vmin=vmin, vmax=vmax) im.remove() add_colorbar(ax,im,label='Meters') ' add contour line(s) ' if contour_lines is not None: nlats, nlons = self.dtm.shape lons, lats = np.meshgrid( np.linspace(self.lonn, self.lonx, nlons), np.linspace(self.latn, self.latx, nlats)) x, y = m(lons, lats) m.contour(x, y, self.dtm, contour_lines, colors='k') ' add coastline' m.drawcoastlines(color='w')
def plot_shaded_map(ax=None, cmap='gist_earth', saveto=None): if ax is None: scale = 0.7 fig, ax = plt.subplots(figsize=(10 * scale, 10 * scale)) # dtmfile = '/home/raul/Github/RadarQC/merged_dem_38-39_123-124_extended.tif' # dtmfile = '/home/raul/Dropbox/NOCAL_DEM/merged_dem_38-39_123-124_extended.tif' dtmfile = '/Users/raulvalenzuela/Dropbox/NOCAL_DEM/merged_dem_38-39_123-124_extended.tif' domain = [-123.4, -122.8, 38.8, 38.1, 8] elev = elevation(file_name=dtmfile, domain=domain) elev.get_elevation() elev_lims = [0, 700] ls = LightSource(azdeg=15, altdeg=60) rgb = ls.shade(elev.dtm, cmap=getattr(plt.cm, cmap), vmin=elev_lims[0], vmax=elev_lims[1], blend_mode='soft', fraction=0.7) ax.imshow(rgb) " interpolate latlon to cartesian coords" nrows, ncols = elev.dtm.shape flat = interp1d(np.linspace(domain[3], domain[2], nrows), range(nrows)) flon = interp1d(np.linspace(domain[0], domain[1], ncols), range(ncols)) lat, lon = locations['FRS'] ax.scatter(flon(lon), flat(lat), color='r', s=50) lat, lon = locations['BBY'] ax.scatter(flon(lon), flat(lat), color='r', s=50) lat, lon = locations['CZD'] ax.scatter(flon(lon), flat(lat), color='r', s=50) 'Use a proxy artist for the colorbar' im = ax.imshow( elev.dtm, cmap=cmap, vmin=elev_lims[0], vmax=elev_lims[1], origin='lower', ) im.remove() add_colorbar(ax, im, label='Meters') ax.set_xticklabels('') ax.set_yticklabels('') plt.tight_layout() if saveto is not None: fname = 'shaded_terrain.png' plt.savefig(saveto + fname, dpi=300, format='png', papertype='letter', bbox_inches='tight')
def plot_elevation_map(self, ax=None, shaded=True, cmap=None, add_loc=None, colorbar=True, blend_mode='overlay', grid=True, gridcolor='w', altitude_range=[-10, 600], contour_lines=None, latdelta=None, londelta=None, homed=None, figsize=None, addrivers=False, add_geoline=None): import os if homed is None: homed = os.path.expanduser('~') ' get elevation model ' if self.source is not None: fname = self.source dtmfile = homed + '/' + fname self.file_name = dtmfile if self.dtm is None: self.get_dem_matfile() else: fname = 'merged_dem_38-39_123-124_extended.tif' dtmfile = homed + '/Github/RadarQC/' + fname self.file_name = dtmfile if self.dtm is None: self.get_elevation() if ax is None: if figsize is None: fig, ax = plt.subplots(figsize=(10, 10)) else: fig, ax = plt.subplots(figsize=figsize) ' make map axis ' m = Basemap(projection='merc', llcrnrlat=self.latn, urcrnrlat=self.latx, llcrnrlon=self.lonn, urcrnrlon=self.lonx, resolution='h', ax=ax) vmin, vmax = altitude_range if shaded: ' make hill shaded image ' ls = LightSource(azdeg=15, altdeg=60) rgb = ls.shade(self.dtm, cmap=getattr(plt.cm, cmap), vmin=vmin, vmax=vmax, blend_mode='soft', fraction=0.7) m.imshow(rgb) else: m.imshow(self.dtm, cmap=cmap, vmin=vmin, vmax=vmax) ' add parallels and meridians ' parallels = np.arange(-90, 90, latdelta) meridians = np.arange(-180, 180, londelta) lw = 0 if grid: lw = 1. parallels = m.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=10, labelstyle='+/-', fmt='%2.1f', linewidth=lw, color=gridcolor) m.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=10, labelstyle='+/-', fmt='%2.1f', linewidth=lw, color=gridcolor) for p in parallels: try: parallels[p][1][0].set_rotation(90) except: pass ' add locations ' if add_loc: fsize = 15 psize = 50 ec = (1.0, 0, 0, 1) fc = (0.5, 0, 0, 1) if isinstance(add_loc, dict): for loc, coord in locations.iteritems(): x, y = m(*coord[::-1]) m.scatter(x, y, psize, color='r') ax.text(x, y, loc, ha='right', va='bottom', color='r', fontsize=fsize, weight='bold') elif isinstance(add_loc, list): for loc in add_loc: coord = locations[loc] x, y = m(*coord[::-1]) m.scatter(x, y, psize, facecolor=fc, edgecolor=ec) ax.text(x, y, loc, ha='right', va='bottom', color='r', fontsize=fsize, weight='bold') ' add section line ' if add_geoline: if isinstance(add_geoline, dict): geolines = list(add_geoline) elif isinstance(add_geoline, list): geolines = add_geoline for line in geolines: x, y = get_line_ini_end(line) self.line_x = x self.line_y = y x, y = m(*[x, y]) if 'color' in line: color = line['color'] else: color = 'k' m.plot(x, y, color=color, linewidth=2) if 'ndiv' in line: ndiv = line['ndiv'] xp = np.linspace(x[0], x[1], ndiv) yp = np.linspace(y[0], y[1], ndiv) m.plot(xp, yp, marker='s', markersize=5, color=color) if 'label' in line: if 'center' in line: x, y = m(*line['center'][::-1]) ax.text(x, y, line['label'] + r'$^\circ$', color=color, weight='bold', fontsize=15, rotation=90 - line['az']) ' add rivers ' if addrivers: rivers = get_rivers(mmap=m) ax.add_collection(rivers) ' add colorbar ' if colorbar: im = m.imshow(self.dtm, cmap=cmap, vmin=vmin, vmax=vmax) im.remove() add_colorbar(ax, im, label='Meters') ' add contour line(s) ' if contour_lines is not None: nlats, nlons = self.dtm.shape lons, lats = np.meshgrid(np.linspace(self.lonn, self.lonx, nlons), np.linspace(self.latn, self.latx, nlats)) x, y = m(lons, lats) m.contour(x, y, self.dtm, contour_lines, colors='k') ' add coastline' m.drawcoastlines(color='w')
def plot(self,target,axes=None,pngsuffix=False, pdfsuffix=False, contourf=True, add_median=False,add_average=False, add_title=True, add_cbar=True,cbar_label=None,show=True, subax_label=True,top_altitude=4000, orientation=None): name={'wdir':'Wind Direction', 'wspd':'Wind Speed', 'u':'u-wind', 'v':'v-wind'} if target == 'wdir': cfad = self.dir_cfad median = self.dir_median average = self.dir_average bins = self.bins_dir hist_xticks = np.arange(0,420,60) hist_xlim = [0,360] elif target == 'wspd': cfad = self.spd_cfad median = self.spd_median average = self.spd_average bins = self.bins_spd hist_xticks = np.arange(0,40,5) hist_xlim = [0,35] elif target == 'u': cfad = self.u_cfad median = self.u_median average = self.u_average bins = self.bins_u hist_xticks = np.arange(-14,22,4) hist_xlim = [-14,20] elif target == 'v': cfad = self.v_cfad median = self.v_median average = self.v_average bins = self.bins_v hist_xticks = np.arange(-14,24,4) hist_xlim = [-14,20] if axes is None: fig,axs = plt.subplots(1,3,sharey=True,figsize=(10,8)) ax1 = axs[0] ax2 = axs[1] ax3 = axs[2] else: ax1 = axes[0] ax2 = axes[1] ax3 = axes[2] hist_wp = np.squeeze(cfad[:,:,0]) hist_wptta = np.squeeze(cfad[:,:,1]) hist_wpnotta = np.squeeze(cfad[:,:,2]) x = bins y = self.hgts if contourf: X,Y = np.meshgrid(x,y) nancol = np.zeros((40,1))+np.nan hist_wp = np.hstack((hist_wp,nancol)) hist_wptta = np.hstack((hist_wptta,nancol)) hist_wpnotta = np.hstack((hist_wpnotta,nancol)) vmax=15 nlevels = 6 delta = int(vmax/nlevels) v = np.arange(2,vmax+delta,delta) cmap = cm.get_cmap('plasma') ax1.contourf(X,Y,hist_wp,v,cmap=cmap) p = ax2.contourf(X,Y,hist_wptta,v,cmap=cmap) ax3.contourf(X,Y,hist_wpnotta,v,cmap=cmap) lcolor = (0.6,0.6,0.6) lw = 3 ax1.vlines(0,0,4000,linestyle='--',color=lcolor,lw=lw) ax2.vlines(0,0,4000,linestyle='--',color=lcolor,lw=lw) ax3.vlines(0,0,4000,linestyle='--',color=lcolor,lw=lw) lw=3 if add_median: ax1.plot(median[:,0],self.hgts,color='w',lw=lw) ax2.plot(median[:,1],self.hgts,color='w',lw=lw) ax3.plot(median[:,2],self.hgts,color='w',lw=lw) if add_average: ax1.plot(average[:,0],self.hgts,color='w',lw=lw) ax2.plot(average[:,1],self.hgts,color='w',lw=lw) ax3.plot(average[:,2],self.hgts,color='w',lw=lw) else: p = ax1.pcolormesh(x,y,hist_wp,cmap='viridis') ax2.pcolormesh(x,y,hist_wptta,cmap='viridis') ax3.pcolormesh(x,y,hist_wpnotta,cmap='viridis') ''' add color bar ''' if add_cbar is True: add_colorbar(ax3,p,size='4%',loc='right', label=cbar_label) ' --- setup ax1 --- ' ax1.set_xticks(hist_xticks) ax1.set_xlim(hist_xlim) ax1.set_ylim([0,top_altitude]) ax1.set_ylabel('Altitude [m] MSL') ' --- setup ax2 --- ' ax2.set_xticks(hist_xticks) ax2.set_xlim(hist_xlim) ax2.set_ylim([0,top_altitude]) ax2.set_xlabel(name[target]) ' --- setup ax3 --- ' ax3.set_xticks(hist_xticks) ax3.set_xlim(hist_xlim) ax3.set_ylim([0,top_altitude]) ''' add subaxis label ''' if orientation == 'horizontal': vpos=1.05 if subax_label is True: txt = 'All profiles (n={})'.format(self.wp_hours) ax1.text(0.5,vpos,txt,fontsize=15,weight='bold', transform=ax1.transAxes,va='center',ha='center') txt = 'TTA (n={})'.format(self.tta_hours) ax2.text(0.5,vpos,txt,fontsize=15,weight='bold', transform=ax2.transAxes,va='center',ha='center') txt = 'NO-TTA (n={})'.format(self.notta_hours) ax3.text(0.5,vpos,txt,fontsize=15, weight='bold', transform=ax3.transAxes,va='center',ha='center') elif orientation == 'vertical': hpos=1.05 if subax_label is True: txt = 'All profiles (n={})'.format(self.wp_hours) ax1.text(hpos,0.5,txt,fontsize=15,weight='bold', transform=ax1.transAxes,va='center', ha='center',rotation=-90) txt = 'TTA (n={})'.format(self.tta_hours) ax2.text(hpos,0.5,txt,fontsize=15,weight='bold', transform=ax2.transAxes,va='center', ha='center',rotation=-90) txt = 'NO-TTA (n={})'.format(self.notta_hours) ax3.text(hpos,0.5,txt,fontsize=15, weight='bold', transform=ax3.transAxes,va='center', ha='center',rotation=-90) ''' add title ''' if add_title is True: title = 'Normalized frequencies of BBY wind profiles {} \n' title += 'TTA wdir_surf:{}, wdir_wp:{}, ' title += 'rain_bby:{}, rain_czd:{}, nhours:{}' if len(self.year) == 1: yy = 'year {}'.format(self.year[0]) else: yy = 'year {} to {}'.format(self.year[0],self.year[-1]) plt.suptitle(title.format(yy, self.wdsurf, self.wdwpro, self.rainbb, self.raincz, self.nhours), fontsize=15) if pngsuffix: out_name = 'wprof_{}_cfad{}.png' plt.savefig(out_name.format(target,pngsuffix)) plt.close() elif pdfsuffix: out_name = 'wprof_{}_cfad{}.pdf' plt.savefig(out_name.format(target,pdfsuffix)) plt.close() if show is True: plt.show() return {'axes':[ax1,ax2,ax3],'im':p}
czdh.values, '-o', lw=2, color=cmap(1), label='CZD') axes[1].plot(np.arange(0.5, 24.5), bbyh.values, '-o', lw=2, color=cmap(0), label='BBY') axes[1].legend(numpoints=1, loc=7) add_colorbar(axes[1], im, invisible=True) axes[1].text(0.05, 0.88, '(b)', ha='right', weight='bold', fontsize=15, transform=axes[1].transAxes) axes[1].text(0.5, 0.88, 'Rainfall', ha='center', weight='bold', fontsize=15,
def plot_colored_staff(ax=None, wspd=None, wdir=None, time=None, height=None, cmap=None, spd_range=None, spd_delta=None, vdensity=None, hdensity=None, title=None, cbar=True): ''' NOAA wind profiler files after year 2000 indicate the start time of averaging period; so a timestamp of 13 UTC indicates average between 13 and 14 UTC There is a bug that plots wrong staff when using meridional winds only ''' from matplotlib import rcParams rcParams['mathtext.default'] = 'sf' spd_array = wspd time_array = time height_array = height ''' make a color map of fixed colors ''' cmap = discrete_cmap(24, base_cmap=cmap, norm_range=[0.1, 0.9]) if len(spd_range) == 2: bounds = range(spd_range[0], spd_range[1] + spd_delta, spd_delta) # vmin = spd_range[0] # vmax = spd_range[1] else: bounds = spd_range # vmin = spd_range[0] # vmax = spd_range[-1] norm = colors.BoundaryNorm(bounds, cmap.N) nrows, ncols = spd_array.shape ''' derive U and V components ''' U = -wspd * np.sin(wdir * np.pi / 180.) V = -wspd * np.cos(wdir * np.pi / 180.) x = np.array(range(len(time))) + 0.5 # wind staff in the middle of pixel # wind staff in the middle of pixel y = np.array(range(height_array.size)) + 0.5 X = np.tile(x, (y.size, 1)) # repeats x y.size times to make 2D array Y = np.tile(y, (x.size, 1)).T # repeates y x.size times to make 2D array Uzero = U - U Vzero = V - V ''' change arrays density ''' if vdensity == 0 or hdensity == 0: pass else: U = fill2D_with_nans(inarray=U, start=[3, 0], size=[vdensity, hdensity]) V = fill2D_with_nans(inarray=V, start=[3, 0], size=[vdensity, hdensity]) ax.barbs(X, Y, U, V, np.sqrt(U * U + V * V), sizes={'height': 0}, length=5, linewidth=0.5, barb_increments={'half': 1}, cmap=cmap, norm=norm) barb = ax.barbs(X, Y, Uzero, Vzero, np.sqrt(U * U + V * V), sizes={'emptybarb': 0.05}, fill_empty=True, cmap=cmap, norm=norm) if isinstance(cbar, maxes._subplots.Axes): hcbar = add_colorbar(cbar, barb, loc='right', label='[m s-1]', labelpad=20, fontsize=12) elif isinstance(cbar, bool) and cbar: hcbar = add_colorbar(ax, barb, loc='right') else: hcbar = None ax.set_xlim([-3.0, len(time_array) + 3.0]) format_xaxis(ax, time_array, delta_hours=1) ax.invert_xaxis() ax.set_xlabel(r'$\leftarrow UTC \left[\stackrel{day}{time}\right]$', fontsize=12) format_yaxis2(ax, height_array) ax.set_ylabel('Altitude MSL [km]') if title is not None: ax.text(0., 1.01, title, transform=ax.transAxes) plt.subplots_adjust(left=0.08, right=0.95) plt.draw() return [ax, hcbar]
def plot_time_height(ax=None, wspd=None, time=None, height=None, spd_range=None, spd_delta=None, cmap=None, title=None, cbar=None, cbarinvi=False, timelabstep=None, kind='pcolormesh', cbar_label=None): ''' NOAA wind profiler files after year 2000 indicate the start time of averaging period; so a timestamp of 13 UTC indicates average between 13 and 14 UTC ''' ''' make a color map of fixed colors ''' if len(spd_range) == 2: bounds = range(spd_range[0], spd_range[1] + spd_delta, spd_delta) else: bounds = spd_range cmap = discrete_cmap(len(bounds) + 1, base_cmap=cmap, norm_range=[0.2, 1.0]) norm = colors.BoundaryNorm(bounds, cmap.N) x = np.linspace(0, len(time), len(time) + 1) y = np.linspace(0, height.size, height.size + 1) wspdm = ma.masked_where(np.isnan(wspd), wspd) # wspdm = ma.masked_where(wspdm<0, wspdm) if kind == 'contourf': x, y = np.meshgrid(np.linspace(0, len(time), len(time)), np.linspace(0, height.size, height.size)) img = ax.contourf(x, y, wspdm, cmap=cmap, norm=norm) else: img = ax.pcolormesh(x, y, wspdm, cmap=cmap, norm=norm) hcbar = add_colorbar(cbar, img, loc='right', label=cbar_label, labelpad=20, fontsize=12, invisible=cbarinvi) ax.set_xlim([-1.0, len(time) + 1.0]) if timelabstep is None: timelabstep = '1H' format_xaxis2(ax, time, timelabstep=timelabstep) ax.invert_xaxis() ax.set_xlabel(r'$\leftarrow UTC \left[\stackrel{day}{time}\right]$', fontsize=20) ax.set_ylabel('Altitude MSL [km]') if title is not None: ax.text(0., 1.01, title, transform=ax.transAxes) plt.subplots_adjust(left=0.08, right=0.95) return [ax, hcbar, img]
def plot_with_hist(year=None,target=None,normalized=True, pngsuffix=None): name={'wdir':'Wind Direction', 'wspd':'Wind Speed'} if target == 'wdir': vmin,vmax = [0,360] bins = np.arange(0,370,10) hist_xticks = np.arange(0,400,40) hist_xlim = [0,360] elif target == 'wspd': vmin,vmax = [0,30] bins = np.arange(0,36,1) hist_xticks = np.arange(0,40,5) hist_xlim = [0,35] fig = plt.figure(figsize=(20,5)) gs = gsp.GridSpec(1, 2, width_ratios=[3,1] ) ax1 = plt.subplot(gs[0]) ax2 = plt.subplot(gs[1]) wprof = parse_data.windprof(year) wp = np.squeeze(pandas2stack(wprof.dframe[target])) wp_ma = ma.masked_where(np.isnan(wp),wp) X,Y = wprof.time,wprof.hgt p = ax1.pcolormesh(X,Y,wp_ma,vmin=vmin,vmax=vmax) add_colorbar(ax1,p) ax1.xaxis.set_major_locator(mdates.MonthLocator()) ax1.xaxis.set_major_formatter(mdates.DateFormatter('%b\n%Y')) ax1.set_xlabel(r'$ Time \rightarrow$') ax1.set_ylabel('Altitude [m] MSL') ax1.set_title('BBY Windprof '+name[target]) array = np.empty((40,len(bins)-1)) for hgt in range(wp.shape[0]): row = wp[hgt,:] freq,bins=np.histogram(row[~np.isnan(row)], bins=bins, density=normalized) array[hgt,:]=freq x = bins y = wprof.hgt p = ax2.pcolormesh(x,y,array,cmap='viridis') amin = np.amin(array) amax = np.amax(array) cbar = add_colorbar(ax2,p,size='4%',ticks=[amin,amax]) cbar.ax.set_yticklabels(['low','high']) ax2.set_xticks(hist_xticks) ax2.set_yticklabels('') ax2.set_xlabel(name[target]) ax2.set_xlim(hist_xlim) ax2.set_title('Normalized frequency') plt.tight_layout() if pngsuffix: out_name = 'wprof_{}_{}.png' plt.savefig(out_name.format(target,pngsuffix)) else: plt.show(block=False)
def plot_with_hist(year=None, target=None, normalized=True, pngsuffix=None): name = {'wdir': 'Wind Direction', 'wspd': 'Wind Speed'} if target == 'wdir': vmin, vmax = [0, 360] bins = np.arange(0, 370, 10) hist_xticks = np.arange(0, 400, 40) hist_xlim = [0, 360] elif target == 'wspd': vmin, vmax = [0, 30] bins = np.arange(0, 36, 1) hist_xticks = np.arange(0, 40, 5) hist_xlim = [0, 35] fig = plt.figure(figsize=(20, 5)) gs = gsp.GridSpec(1, 2, width_ratios=[3, 1]) ax1 = plt.subplot(gs[0]) ax2 = plt.subplot(gs[1]) wprof = parse_data.windprof(year) wp = np.squeeze(pandas2stack(wprof.dframe[target])) wp_ma = ma.masked_where(np.isnan(wp), wp) X, Y = wprof.time, wprof.hgt p = ax1.pcolormesh(X, Y, wp_ma, vmin=vmin, vmax=vmax) add_colorbar(ax1, p) ax1.xaxis.set_major_locator(mdates.MonthLocator()) ax1.xaxis.set_major_formatter(mdates.DateFormatter('%b\n%Y')) ax1.set_xlabel(r'$ Time \rightarrow$') ax1.set_ylabel('Altitude [m] MSL') ax1.set_title('BBY Windprof ' + name[target]) array = np.empty((40, len(bins) - 1)) for hgt in range(wp.shape[0]): row = wp[hgt, :] freq, bins = np.histogram(row[~np.isnan(row)], bins=bins, density=normalized) array[hgt, :] = freq x = bins y = wprof.hgt p = ax2.pcolormesh(x, y, array, cmap='viridis') amin = np.amin(array) amax = np.amax(array) cbar = add_colorbar(ax2, p, size='4%', ticks=[amin, amax]) cbar.ax.set_yticklabels(['low', 'high']) ax2.set_xticks(hist_xticks) ax2.set_yticklabels('') ax2.set_xlabel(name[target]) ax2.set_xlim(hist_xlim) ax2.set_title('Normalized frequency') plt.tight_layout() if pngsuffix: out_name = 'wprof_{}_{}.png' plt.savefig(out_name.format(target, pngsuffix)) else: plt.show(block=False)
def plot_sector(filein=None, ax=None, latlabel=True, lonlabel=True, labels=True, colorbar=False, cbarpos='top', sector=None, target=None, boundary=None, id=None): latn = sector['latn'] latx = sector['latx'] lonn = sector['lonn'] lonx = sector['lonx'] lw = boundary['lw'] color = boundary['color'] data = Dataset(filein, 'r') lats = data.variables['lat'][:] lons = data.variables['lon'][:] idxlon = np.where((lons > lonn) & (lons < lonx))[0] idxlat = np.where((lats > latn) & (lats < latx))[0] array = np.squeeze(data.variables[target][:, idxlat, idxlon]) - 273.15 data.close() lats2 = lats[idxlat] lons2 = lons[idxlon] if target == 'irwin_cdr': mycmap = goes_cmap(type='ir') elif target == 'irwvp': mycmap = goes_cmap(type='wvp') im = ax.pcolormesh( lons2, lats2, array, cmap=mycmap, vmax=20, vmin=-60, ) add_boundaries(ax, sector, lw=lw, color=color) latlabels = ['', '50S', '', '40', '', '30', ''] ax.set_yticklabels(latlabels, rotation=90) lonlabels = ['123', '100W', '90', '80', '70'] ax.set_xticklabels(lonlabels) ax.set_xlim([lonn, lonx]) ax.set_ylim([latn, latx]) if labels is False: ax.set_xticklabels([]) ax.set_yticklabels([]) elif latlabel is False: ax.set_yticklabels([]) elif lonlabel is False: ax.set_xticklabels([]) if colorbar: cbar = add_colorbar(ax, im, loc=cbarpos, size='10%', label='', ticks_everyother=True, fontsize=12) # cbar.ax.invert_xaxis() cbar.ax.invert_yaxis() if id is not None: ax.text(0.05, 0.9, id, fontsize=14, color='w', weight='bold', transform=ax.transAxes) plt.draw()
newxtl.append(lb) else: newxtl.append(lb.get_text()) ax.set_xticklabels(newxtl) ax.set_ylim([-13, 30]) ax.set_xlim([24, 0]) " line plots " cmap = discrete_cmap(7, base_cmap='Set1') axes[1].plot(np.arange(0.5, 24.5), czdh.values, '-o', lw=2, color=cmap(1), label='CZD') axes[1].plot(np.arange(0.5, 24.5), bbyh.values, '-o', lw=2, color=cmap(0), label='BBY') add_colorbar(axes[1], im, invisible=True) axes[1].legend(numpoints=1, loc=5) # ax2 = axes[1].twinx() # ax2.plot(np.arange(0.5, 24.5), czdh.values/bbyh.values, # '-o', lw=2, color=(0, 0, 0)) # add_colorbar(ax2, im, invisible=True) axes[1].text(0.95, 0.85, '16 February 2004', ha='right', weight='bold', fontsize=15, transform=axes[1].transAxes) axes[1].invert_xaxis() # axes[1].grid(True) axes[1].set_xticks(range(0, 23, 3)) axes[1].set_xlim([24, 0]) axes[1].set_xticklabels('')
def plot(year=[],target=None,pngsuffix=False, normalized=True, contourf=True, pdfsuffix=False, wdsurf=None, wdwpro=None, rainbb=None, raincz=None, nhours=None): name={'wdir':'Wind Direction', 'wspd':'Wind Speed'} if target == 'wdir': bins = np.arange(0,370,10) hist_xticks = np.arange(0,420,60) hist_xlim = [0,360] elif target == 'wspd': bins = np.arange(0,36,1) hist_xticks = np.arange(0,40,5) hist_xlim = [0,35] first = True for y in year: print('Processing year {}'.format(y)) ' tta analysis ' tta = tta_analysis(y) tta.start_df(wdir_surf=wdsurf, wdir_wprof=wdwpro, rain_bby=rainbb, rain_czd=raincz, nhours=nhours) ' retrieve dates ' include_dates = tta.include_dates tta_dates = tta.tta_dates notta_dates = tta.notta_dates ' read wprof ' wprof_df = parse_data.windprof(y) wprof = wprof_df.dframe[target] ' wprof partition ' wprof = wprof.loc[include_dates] # all included wprof_tta = wprof.loc[tta_dates] # only tta wprof_notta = wprof.loc[notta_dates]# only notta s1 = np.squeeze(pandas2stack(wprof)) s2 = np.squeeze(pandas2stack(wprof_tta)) s3 = np.squeeze(pandas2stack(wprof_notta)) if first: wp = s1 wp_tta = s2 wp_notta = s3 first = False else: wp = np.hstack((wp,s1)) wp_tta = np.hstack((wp_tta,s2)) wp_notta = np.hstack((wp_notta, s3)) _,wp_hours = wp.shape _,tta_hours = wp_tta.shape _,notta_hours = wp_notta.shape ' makes CFAD ' hist_array = np.empty((40,len(bins)-1,3)) for hgt in range(wp.shape[0]): row1 = wp[hgt,:] row2 = wp_tta[hgt,:] row3 = wp_notta[hgt,:] for n,r in enumerate([row1,row2,row3]): ' following CFAD Yuter et al (1995) ' freq,bins=np.histogram(r[~np.isnan(r)], bins=bins) if normalized: hist_array[hgt,:,n] = 100.*(freq/float(freq.sum())) else: hist_array[hgt,:,n] = freq fig,axs = plt.subplots(1,3,sharey=True,figsize=(10,8)) ax1 = axs[0] ax2 = axs[1] ax3 = axs[2] hist_wp = np.squeeze(hist_array[:,:,0]) hist_wptta = np.squeeze(hist_array[:,:,1]) hist_wpnotta = np.squeeze(hist_array[:,:,2]) x = bins y = wprof_df.hgt if contourf: X,Y = np.meshgrid(x,y) nancol = np.zeros((40,1))+np.nan hist_wp = np.hstack((hist_wp,nancol)) hist_wptta = np.hstack((hist_wptta,nancol)) hist_wpnotta = np.hstack((hist_wpnotta,nancol)) vmax=20 nlevels = 10 delta = int(vmax/nlevels) v = np.arange(2,vmax+delta,delta) cmap = cm.get_cmap('plasma') ax1.contourf(X,Y,hist_wp,v,cmap=cmap) p = ax2.contourf(X,Y,hist_wptta,v,cmap=cmap,extend='max') p.cmap.set_over(cmap(1.0)) ax3.contourf(X,Y,hist_wpnotta,v,cmap=cmap) cbar = add_colorbar(ax3,p,size='4%') else: p = ax1.pcolormesh(x,y,hist_wp,cmap='viridis') ax2.pcolormesh(x,y,hist_wptta,cmap='viridis') ax3.pcolormesh(x,y,hist_wpnotta,cmap='viridis') amin = np.amin(hist_wpnotta) amax = np.amax(hist_wpnotta) cbar = add_colorbar(ax3,p,size='4%',ticks=[amin,amax]) cbar.ax.set_yticklabels(['low','high']) ' --- setup ax1 --- ' amin = np.amin(hist_wp) amax = np.amax(hist_wp) ax1.set_xticks(hist_xticks) ax1.set_xlim(hist_xlim) ax1.set_ylim([0,4000]) txt = 'All profiles (n={})'.format(wp_hours) ax1.text(0.5,0.95,txt,fontsize=15, transform=ax1.transAxes,va='bottom',ha='center') ax1.set_ylabel('Altitude [m] MSL') ' --- setup ax2 --- ' amin = np.amin(hist_wptta) amax = np.amax(hist_wptta) ax2.set_xticks(hist_xticks) ax2.set_xlim(hist_xlim) ax2.set_ylim([0,4000]) ax2.set_xlabel(name[target]) txt = 'TTA (n={})'.format(tta_hours) ax2.text(0.5,0.95,txt,fontsize=15, transform=ax2.transAxes,va='bottom',ha='center') ' --- setup ax3 --- ' ax3.set_xticks(hist_xticks) ax3.set_xlim(hist_xlim) ax3.set_ylim([0,4000]) txt = 'NO-TTA (n={})'.format(notta_hours) ax3.text(0.5,0.95,txt,fontsize=15, transform=ax3.transAxes,va='bottom',ha='center') title = 'Normalized frequencies of BBY wind profiles {} \n' title += 'TTA wdir_surf:{}, wdir_wp:{}, ' title += 'rain_bby:{}, rain_czd:{}, nhours:{}' if len(year) == 1: yy = 'year {}'.format(year[0]) else: yy = 'year {} to {}'.format(year[0],year[-1]) plt.suptitle(title.format(yy, wdsurf, wdwpro, rainbb, raincz, nhours), fontsize=15) plt.subplots_adjust(top=0.9,left=0.1,right=0.95,bottom=0.1, wspace=0.1) if pngsuffix: out_name = 'wprof_{}_cfad{}.png' plt.savefig(out_name.format(target,pngsuffix)) plt.close() elif pdfsuffix: out_name = 'wprof_{}_cfad{}.pdf' plt.savefig(out_name.format(target,pdfsuffix)) plt.close() else: plt.show()