def test_skewt_shade_area_invalid(test_profile): """Test shading areas on a SkewT plot.""" p, t, tp = test_profile fig = plt.figure(figsize=(9, 9)) skew = SkewT(fig) skew.plot(p, t, 'r') skew.plot(p, tp, 'k') with pytest.raises(ValueError): skew.shade_area(p, t, tp, which='positve')
def plot_sounding(date, station): p, T, Td, u, v, windspeed = get_sounding_data(date, station) lcl_pressure, lcl_temperature = mpcalc.lcl(p[0], T[0], Td[0]) lfc_pressure, lfc_temperature = mpcalc.lfc(p, T, Td) parcel_path = mpcalc.parcel_profile(p, T[0], Td[0]).to('degC') # Create a new figure. The dimensions here give a good aspect ratio fig = plt.figure(figsize=(8, 8)) skew = SkewT(fig) # Plot the data temperature_line, = skew.plot(p, T, color='tab:red') dewpoint_line, = skew.plot(p, Td, color='blue') cursor = mplcursors.cursor([temperature_line, dewpoint_line]) # Plot thermodynamic parameters and parcel path skew.plot(p, parcel_path, color='black') if lcl_pressure: skew.ax.axhline(lcl_pressure, color='black') if lfc_pressure: skew.ax.axhline(lfc_pressure, color='0.7') # Add the relevant special lines skew.ax.axvline(0, color='c', linestyle='--', linewidth=2) skew.plot_dry_adiabats() skew.plot_moist_adiabats() skew.plot_mixing_lines() # Shade areas representing CAPE and CIN skew.shade_cin(p, T, parcel_path) skew.shade_cape(p, T, parcel_path) # Add wind barbs skew.plot_barbs(p, u, v) # Add an axes to the plot ax_hod = inset_axes(skew.ax, '30%', '30%', loc=1, borderpad=3) # Plot the hodograph h = Hodograph(ax_hod, component_range=100.) # Grid the hodograph h.add_grid(increment=20) # Plot the data on the hodograph mask = (p >= 100 * units.mbar) h.plot_colormapped(u[mask], v[mask], windspeed[mask]) # Plot a line colored by wind speed # Set some sensible axis limits skew.ax.set_ylim(1000, 100) skew.ax.set_xlim(-40, 60) return fig, skew
def test_skewt_shade_area(test_profile): """Test shading areas on a SkewT plot.""" p, t, tp = test_profile fig = plt.figure(figsize=(9, 9)) skew = SkewT(fig) skew.plot(p, t, 'r') skew.plot(p, tp, 'k') skew.shade_area(p, t, tp) skew.ax.set_xlim(-50, 50) return fig
def test_skewt_shade_cape_cin(test_profile): """Test shading CAPE and CIN on a SkewT plot.""" p, t, tp = test_profile fig = plt.figure(figsize=(9, 9)) skew = SkewT(fig) skew.plot(p, t, 'r') skew.plot(p, tp, 'k') skew.shade_cape(p, t, tp) skew.shade_cin(p, t, tp) skew.ax.set_xlim(-50, 50) return fig
def test_skewt_shade_area_kwargs(test_profile): """Test shading areas on a SkewT plot with kwargs.""" p, t, tp = test_profile with matplotlib.rc_context({'axes.autolimit_mode': 'data'}): fig = plt.figure(figsize=(9, 9)) skew = SkewT(fig) skew.plot(p, t, 'r') skew.plot(p, tp, 'k') skew.shade_area(p, t, tp, facecolor='m') skew.ax.set_xlim(-50, 50) return fig
def test_skewt_shade_cape_cin(test_profile): """Test shading CAPE and CIN on a SkewT plot.""" p, t, tp = test_profile with matplotlib.rc_context({'axes.autolimit_mode': 'data'}): fig = plt.figure(figsize=(9, 9)) skew = SkewT(fig) skew.plot(p, t, 'r') skew.plot(p, tp, 'k') skew.shade_cape(p, t, tp) skew.shade_cin(p, t, tp) skew.ax.set_xlim(-50, 50) return fig
def test_skewt_api(): """Test the SkewT API.""" fig = plt.figure(figsize=(9, 9)) skew = SkewT(fig) # Plot the data using normal plotting functions, in this case using # log scaling in Y, as dictated by the typical meteorological plot p = np.linspace(1000, 100, 10) t = np.linspace(20, -20, 10) u = np.linspace(-10, 10, 10) skew.plot(p, t, 'r') skew.plot_barbs(p, u, u) # Add the relevant special lines skew.plot_dry_adiabats() skew.plot_moist_adiabats() skew.plot_mixing_lines() return fig
def test_skewt_api(): """Test the SkewT API.""" with matplotlib.rc_context({'axes.autolimit_mode': 'data'}): fig = plt.figure(figsize=(9, 9)) skew = SkewT(fig) # Plot the data using normal plotting functions, in this case using # log scaling in Y, as dictated by the typical meteorological plot p = np.linspace(1000, 100, 10) t = np.linspace(20, -20, 10) u = np.linspace(-10, 10, 10) skew.plot(p, t, 'r') skew.plot_barbs(p, u, u) skew.ax.set_xlim(-20, 30) skew.ax.set_ylim(1000, 100) # Add the relevant special lines skew.plot_dry_adiabats() skew.plot_moist_adiabats() skew.plot_mixing_lines() return fig
def plot_sounding(date, station): p, T, Td, u, v, windspeed = get_sounding_data(date, station) lcl_pressure, lcl_temperature = mpcalc.lcl(p[0], T[0], Td[0]) lfc_pressure, lfc_temperature = mpcalc.lfc(p, T, Td) parcel_path = mpcalc.parcel_profile(p, T[0], Td[0]).to('degC') # Create a new figure. The dimensions here give a good aspect ratio fig = plt.figure(figsize=(8, 8)) skew = SkewT(fig) # Plot the data skew.plot(p, T, color='tab:red') skew.plot(p, Td, color='tab:green') # Plot thermodynamic parameters and parcel path skew.plot(p, parcel_path, color='black') if lcl_pressure: skew.ax.axhline(lcl_pressure, color='black') if lfc_pressure: skew.ax.axhline(lfc_pressure, color='0.7') # Add the relevant special lines skew.ax.axvline(0, color='c', linestyle='--', linewidth=2) skew.plot_dry_adiabats() skew.plot_moist_adiabats() skew.plot_mixing_lines() # Shade areas representing CAPE and CIN skew.shade_cin(p, T, parcel_path) skew.shade_cape(p, T, parcel_path) # Add wind barbs skew.plot_barbs(p, u, v) # Add an axes to the plot ax_hod = inset_axes(skew.ax, '30%', '30%', loc=1, borderpad=3) # Plot the hodograph h = Hodograph(ax_hod, component_range=100.) # Grid the hodograph h.add_grid(increment=20) # Plot the data on the hodograph mask = (p >= 100 * units.mbar) h.plot_colormapped(u[mask], v[mask], windspeed[mask]) # Plot a line colored by wind speed # Set some sensible axis limits skew.ax.set_ylim(1000, 100) skew.ax.set_xlim(-40, 60) return fig, skew
def Skew_T_diagram(T, z, wv): """ Plot a Skew-T diagram. Credits @ MetPy: https://unidata.github.io/MetPy/latest/index.html """ from metpy.plots import SkewT P = P_env(z) / 100 wvs = wv_sat(T, z) Td = T_dew(wv, z) env = T_env(z) zLCL = np.argmin(abs(T - Td)) P_LCL = P[:zLCL] Td = Td[:zLCL] fig = plt.figure(figsize=(11, 11)) skew = SkewT(fig, rotation=45) skew.plot(P_LCL, Td, 'b', linewidth=3, label='T_dew') skew.plot(P, T, 'r', linewidth=3, label='T_parc') skew.plot(P, env, 'g', linewidth=3, label='T_env') skew.plot_dry_adiabats() skew.plot_moist_adiabats() skew.plot_mixing_lines() skew.ax.set_ylim(1010, 100) skew.plot(P[zLCL], T[zLCL], '.k', markersize=15, label='LCL = %.1f km' % np.round(z[zLCL] / 1000, 1)) skew.shade_cin(P[zLCL:], env[zLCL:], T[zLCL:], label='Level above LFC') skew.shade_cape(P[zLCL:], env[zLCL:], T[zLCL:], label='CAPE') plt.legend() skew.ax.set_xlim(-30, 40) skew.ax.set_xlabel('Temperature [C]') skew.ax.set_ylabel('Pressure [hPa]') skew.ax.set_title('Skew-T diagram Essen Sounding') return plt.show()
def plot_skewt(df): # We will pull the data out of the example dataset into individual variables # and assign units. p = df['pressure'].values * units.hPa T = df['temperature'].values * units.degC Td = df['dewpoint'].values * units.degC wind_speed = df['speed'].values * units.knots wind_dir = df['direction'].values * units.degrees u, v = mpcalc.wind_components(wind_speed, wind_dir) # Create a new figure. The dimensions here give a good aspect ratio. fig = plt.figure(figsize=(9, 9)) add_metpy_logo(fig, 115, 100) skew = SkewT(fig, rotation=45) # Plot the data using normal plotting functions, in this case using # log scaling in Y, as dictated by the typical meteorological plot skew.plot(p, T, 'r') skew.plot(p, Td, 'g') skew.plot_barbs(p, u, v) skew.ax.set_ylim(1000, 100) skew.ax.set_xlim(-40, 60) # Calculate LCL height and plot as black dot lcl_pressure, lcl_temperature = mpcalc.lcl(p[0], T[0], Td[0]) skew.plot(lcl_pressure, lcl_temperature, 'ko', markerfacecolor='black') # Calculate full parcel profile and add to plot as black line prof = mpcalc.parcel_profile(p, T[0], Td[0]).to('degC') skew.plot(p, prof, 'k', linewidth=2) # An example of a slanted line at constant T -- in this case the 0 # isotherm skew.ax.axvline(0, color='c', linestyle='--', linewidth=2) # Add the relevant special lines skew.plot_dry_adiabats() skew.plot_moist_adiabats() skew.plot_mixing_lines() return skew
def plot_skew(sound_path=sound_path, date='2018-01-16T12:00', two=False): from metpy.plots import SkewT from metpy.units import units import matplotlib.pyplot as plt import pandas as pd import xarray as xr da = xr.open_dataarray(sound_path / 'ALL_bet_dagan_soundings.nc') p = da.sel(time=date, var='PRES').values * units.hPa dt = pd.to_datetime(da.sel(time=date).time.values) if not two: T = da.sel(time=date, var='TEMP').values * units.degC Td = da.sel(time=date, var='DWPT').values * units.degC Vp = VaporPressure(da.sel(time=date, var='TEMP').values) * units.Pa dt = pd.to_datetime(da.sel(time=date).time.values) fig = plt.figure(figsize=(9, 9)) title = da.attrs['description'] + ' ' + dt.strftime('%Y-%m-%d %H:%M') skew = SkewT(fig) skew.plot(p, T, 'r', linewidth=2) skew.plot(p, Td, 'g', linewidth=2) # skew.ax.plot(p, Vp, 'k', linewidth=2) skew.ax.set_title(title) skew.ax.legend(['Temp', 'Dewpoint']) elif two: dt1 = pd.to_datetime(dt.strftime('%Y-%m-%dT00:00')) dt2 = pd.to_datetime(dt.strftime('%Y-%m-%dT12:00')) T1 = da.sel(time=dt1, var='TEMP').values * units.degC T2 = da.sel(time=dt2, var='TEMP').values * units.degC fig = plt.figure(figsize=(9, 9)) title = da.attrs['description'] + ' ' + dt.strftime('%Y-%m-%d') skew = SkewT(fig) skew.plot(p, T1, 'r', linewidth=2) skew.plot(p, T2, 'b', linewidth=2) # skew.ax.plot(p, Vp, 'k', linewidth=2) skew.ax.set_title(title) skew.ax.legend([ 'Temp at ' + dt1.strftime('%H:%M'), 'Temp at ' + dt2.strftime('%H:%M') ]) return
def plot_skewt(self): """ :param adjusted_data: receives the post processed dataframe :param valid: :return: """ for area in self.airports: for airport in self.airports[area]: lon = self.airports[area][airport]['lon'] lat = self.airports[area][airport]['lat'] pressure_levels = self.levels * units.hPa tair = list( self.create_profile_variable(self.tair, lat, lon).values()) * units.degC dewp = list( self.create_profile_variable(self.dewp, lat, lon).values()) * units.degC u_wnd = list(self.create_profile_variable(self.u_wnd, lat, lon).values()) * \ units('meters / second').to('knots') v_wnd = list(self.create_profile_variable(self.v_wnd, lat, lon).values()) * \ units('meters / second').to('knots') # Create a new figure. The dimensions here give a good aspect ratio. fig = plt.figure(figsize=(12, 9)) skew = SkewT(fig, rotation=45) # Plot the data using normal plotting functions, in this case using # log scaling in Y, as dictated by the typical meteorological plot skew.plot(pressure_levels, tair, 'r') skew.plot(pressure_levels, dewp, 'g') skew.plot_barbs(pressure_levels, u_wnd, v_wnd) skew.ax.set_ylim(1020, 100) skew.ax.set_xlim(-40, 60) # Calculate LCL height and plot as black dot lcl_pressure, lcl_temperature = mpcalc.lcl( pressure_levels[0], tair[0], dewp[0]) skew.plot(lcl_pressure, lcl_temperature, 'ko', markerfacecolor='black') # Calculate full parcel profile and add to plot as black line prof = mpcalc.parcel_profile(pressure_levels, tair[0], dewp[0]) skew.plot(pressure_levels, prof, 'k', linewidth=2) # An example of a slanted line at constant T -- in this case the 0 # isotherm skew.ax.axvline(0, color='c', linestyle='--', linewidth=2) # Add the relevant special lines skew.plot_dry_adiabats() skew.plot_moist_adiabats() skew.plot_mixing_lines() skew.shade_cape(pressure_levels, tair, prof) skew.shade_cin(pressure_levels, tair, prof) plt.title( f'Perfil vertical (GFS) de {airport} valido para {self.time_stamp}', fontsize=16, ha='center') sounding_output_path = f'{self.output_path}/{area}/{airport}' Path(sounding_output_path).mkdir(parents=True, exist_ok=True) plt.savefig( f'{sounding_output_path}/sounding_{airport}_{self.time_step:02d}.jpg' ) return skew
print('Calculating moist adiabats...') for i in range(N_sample_pts): if i % 10 == 0: print(i) T_data[i, :] = moist_lapse(temperature=T_data[i, 0] * units('K'), pressure=pressures * units('Pa')) # Keep T constant above 200 hPa for a Tropopause for i in range(len(pressures)): if pressures[i] / 100 < 200: T_data[:, i] = T_data[:, i - 1] # Debug plots: f = plt.figure(figsize=(9, 9)) skew = SkewT(f, rotation=45) for i in range(N_sample_pts): skew.plot(pressures / 100, T_data[i, :] - 273.15, 'r') skew.ax.set_ylim(1000, 100) skew.ax.set_xlim(minT - 273.15 - 5, maxT - 273.15 + 5) skew.plot_moist_adiabats() plt.show() # Save data fname = 'moist_adiabat_data.npz' np.savez(fname, pressures=pressures, T_surf_sample=T_surf_sample, T_data=T_data) print('Data saved in {}.'.format(fname))
dataset = get_upper_air_data(datetime(1999, 5, 4, 0), 'OUN') p = dataset.variables['pressure'][:] T = dataset.variables['temperature'][:] Td = dataset.variables['dewpoint'][:] u = dataset.variables['u_wind'][:] v = dataset.variables['v_wind'][:] ########################################### # Create a new figure. The dimensions here give a good aspect ratio fig = plt.figure(figsize=(9, 9)) skew = SkewT(fig, rotation=45) # Plot the data using normal plotting functions, in this case using # log scaling in Y, as dictated by the typical meteorological plot skew.plot(p, T, 'r') skew.plot(p, Td, 'g') skew.plot_barbs(p, u, v) skew.ax.set_ylim(1000, 100) skew.ax.set_xlim(-40, 60) # Calculate LCL height and plot as black dot l = mpcalc.lcl(p[0], T[0], Td[0]) lcl_temp = mpcalc.dry_lapse(concatenate((p[0], l)), T[0])[-1].to('degC') skew.plot(l, lcl_temp, 'ko', markerfacecolor='black') # Calculate full parcel profile and add to plot as black line prof = mpcalc.parcel_profile(p, T[0], Td[0]).to('degC') skew.plot(p, prof, 'k', linewidth=2) # Example of coloring area between profiles
p = dataset['pressure'].values * units(dataset.units['pressure']) #ip100 = np.where(p.magnitude==100.)[0][0]+1 #p = p[:ip100] T = dataset['temperature'].values * units(dataset.units['temperature']) #T = T[:ip100] Td = dataset['dewpoint'].values * units(dataset.units['dewpoint']) #Td = Td[:ip100] u = dataset['u_wind'].values * units(dataset.units['u_wind']) #u = u[:ip100] v = dataset['v_wind'].values * units(dataset.units['v_wind']) #v = v[:ip100] fig = plt.figure(figsize=(9, 9)) skew = SkewT(fig) skew.plot(p, T, 'r') skew.plot(p, Td, 'g') skew.plot_barbs(p[:-1:2], u[:-1:2], v[:-1:2]) skew.plot_dry_adiabats() skew.plot_moist_adiabats() skew.plot_mixing_lines() skew.ax.set_ylim(1000, 100) skew.ax.set_xlim(-40, 60) prof = metcalc.parcel_profile(p, T[0], Td[0]).to('degC') skew.plot(p, prof, 'k', linewidth=2) plt.title('KILX ROAB Obs 00 UTC 27 June 2018', loc='center') plt.savefig( '/home/jhemedinger/suli_projects/chicago-nowcast/images/ilx_sounding_00UTC.png', dpi=300) plt.show()
# Wind shear bulkshear = wind_kts[-3] - wind_kts[0] print '0-{0:.0f} m Bulk Shear: {1:.0f} kts'.format(sampleHeights_m[-3], bulkshear) ###################### ## Create SkewTLogP ## ###################### print 'Plotting...' fig5 = plt.figure(figsize=(10.125, 9)) gs = gridspec.GridSpec(5, 4) skew = SkewT(fig5, rotation=20, subplot=gs[:, :2]) skew.plot(pres, Tmean, 'r', linewidth=2) skew.plot(pres, Td, 'g', linewidth=2) skew.plot_barbs(pres[0::4], u[0::4], v[0::4], x_clip_radius = 0.12, \ y_clip_radius = 0.12) # Plot mesonet surface data and winds skew.plot(pmeso, T2meso, 'k*', linewidth=2, label='Mesonet 2 m T') skew.plot(pres[0], T9meso, 'r*', linewidth=2, label='Mesonet 9 m T') skew.plot(pmeso, Td2meso, 'g*', linewidth=2, label='Mesonet 2 m Td') skew.plot_barbs(pmeso, umeso, vmeso, barbcolor='r', label='Mesonet 10 m Wind') hand, lab = skew.ax.get_legend_handles_labels() # Plot convective parameters if isRH: skew.plot(lclpres, lcltemp, 'ko', markerfacecolor='black')
# # 3. Plot the pressure and temperature (note that the pressure, # the independent variable, is first even though it is plotted on the y-axis). # # 4. Plot the pressure and dewpoint temperature. # # 5. Plot the wind barbs at the appropriate pressure using the u and v wind # components. # Create a new figure. The dimensions here give a good aspect ratio fig = plt.figure(figsize=(9, 9)) skew = SkewT(fig) # Plot the data using normal plotting functions, in this case using # log scaling in Y, as dictated by the typical meteorological plot skew.plot(p, T, 'r', linewidth=2) skew.plot(p, Td, 'g', linewidth=2) skew.plot_barbs(p, u, v) # Show the plot plt.show() ########################################################################## # Advanced Skew-T Plotting # ------------------------ # # Fiducial lines indicating dry adiabats, moist adiabats, and mixing ratio are # useful when performing further analysis on the Skew-T diagram. Often the # 0C isotherm is emphasized and areas of CAPE and CIN are shaded. # Create a new figure. The dimensions here give a good aspect ratio
rho = atmos.calculate('rho', **data) dpdz = rho * 9.8 heights = np.zeros_like(p) heights[0] = 10.0 for i in range(1,len(heights)): heights[i] = ((((p[i-1] - p[i])*100.)) / dpdz[i-1]) + heights[i-1] p=p*units.hPa45 T=T*units.degC Td=Td*units.degC fig = plt.figure(figsize=(9, 9))45 skew = SkewT(fig, rotation=45) skew.plot(p, T, 'r',linewidth=2) skew.plot(p, Td, 'g',linewidth=2) skew.plot_barbs(p, u, v) skew.ax.set_ylim(1000, 100) skew.ax.set_xlim(-40,60) cape, cin, prof = get_cape(filename,'ml') print cape prof = prof-273.15 skew.plot(p, prof, 'k') skew.plot_dry_adiabats() skew.plot_moist_adiabats() skew.plot_mixing_lines() #skew.ax.set_title('August 11')
def plotUAVskewT(filenamecsv): ''' Input filepath of post-processed uav data Outputs Skew-T log-p plot of UAV data, includes hodograph and some convective parameters ''' copdata = csvread_copter(filenamecsv) lat = copdata[0] lon = copdata[1] alt = copdata[2] pressure = copdata[3] temperature = copdata[4] dewpoint = copdata[5] speed = copdata[9] speed_kts = speed * 1.94 direction = copdata[10] site = findSite(lat[0], lon[0]) sitename, sitelong = site.split('/') fname = filenamecsv.split('\\')[-1] timeTakeoff = datetime.strptime(fname[:15], '%Y%m%d_%H%M%S') copterNum = fname[-10] u,v = mcalc.get_wind_components(speed_kts*units.kts, direction * units.deg) u = u.to(units.kts) v = v.to(units.kts) # Wind shear bulkshear = speed_kts[-3] - speed_kts[0] print '0-%d m Bulk Shear: %.0f kts' % (alt[-3], bulkshear) if np.isnan(dewpoint).all(): moist = 0 else: moist = 1 print 'Plotting...' fignum = plt.figure(figsize=(12,9)) gs = gridspec.GridSpec(4, 4) skew = SkewT(fignum, rotation=20, subplot=gs[:, :2]) skew.plot(pressure, temperature, 'r', linewidth = 2) skew.plot(pressure, dewpoint, 'g', linewidth = 2) skew.plot_barbs(pressure[0::4], u[0::4], v[0::4], x_clip_radius = 0.12, \ y_clip_radius = 0.12) # Plot convective parameters if moist: plcl, Tlcl, isbelowlcl, profile = parcelUAV(temperature, dewpoint, pressure) SBCAPE = uavCAPE(temperature * units.degC, profile, pressure * units.hPa) skew.plot(plcl, Tlcl, 'ko', markerfacecolor='black') skew.plot(pressure, profile, 'k', linewidth=2) else: isbelowlcl = 0 # set up plot limits and labels - use LCL as max if higher than profile # if moist: # xmin = math.floor(np.nanmin(dewpoint)) + 2 # else: # xmin = math.floor(np.nanmin(temperature)) # xmax = math.floor(np.nanmax(temperature)) + 20 xmin = 0. xmax = 50. if isbelowlcl: ymin = round((plcl / units.mbar), -1) - 10 else: ymin = round(np.nanmin(pressure),-1) - 10 ymax = round(np.nanmax(pressure),-1) + 10 skew.ax.set_ylim(ymax, ymin) skew.ax.set_xlim(xmin, xmax) skew.ax.set_yticks(np.arange(ymin, ymax+10, 10)) skew.ax.set_xlabel('Temperature ($^\circ$C)') skew.ax.set_ylabel('Pressure (hPa)') titleName = 'Coptersonde-%s %s UTC - %s' % (copterNum, timeTakeoff.strftime('%d-%b-%Y %H:%M:%S'), sitename) skew.ax.set_title(titleName) skew.plot_dry_adiabats(linewidth=0.75) skew.plot_moist_adiabats(linewidth=0.75) skew.plot_mixing_lines(linewidth=0.75) # Hodograph ax_hod = fignum.add_subplot(gs[:2,2:]) #gs.tight_layout(fig5) if np.nanmax(speed_kts) > 18: comprange = 35 else: comprange = 20 h = Hodograph(ax_hod, component_range=comprange) h.add_grid(increment=5) h.plot_colormapped(u, v, pressure, cmap=cmocean.cm.deep_r) ax_hod.set_title('Hodograph (kts)') ax_hod.yaxis.set_ticklabels([]) #ax_hod.set_xlabel('Wind Speed (kts)') # Map - Oklahoma llcrnrlat = 33.6 urcrnrlat = 37.2 llcrnrlon = -103.2 urcrnrlon = -94.2 ax_map = fignum.add_subplot(gs[2, 2:]) m = Basemap(projection='merc', llcrnrlat=llcrnrlat, urcrnrlat=urcrnrlat, llcrnrlon=llcrnrlon,urcrnrlon=urcrnrlon, lat_ts=20, resolution='l', ax=ax_map) print 'Basemap...' m.drawcounties() m.drawstates() x,y = m(lon[0], lat[0]) plt.plot(x,y,'b.') plt.text(x+40000, y-5000, sitelong, bbox=dict(facecolor='yellow', alpha=0.5)) if moist: # Convective parameter values ax_data = fignum.add_subplot(gs[3, 2]) plt.axis('off') datastr = 'LCL = %.0f hPa\nSBCAPE = %.0f J kg$^{-1}$\n0-%.0f m bulk shear\n\ = %.0f kts' % \ (plcl.magnitude, SBCAPE.magnitude, alt[-3], bulkshear) boxprops = dict(boxstyle='round', facecolor='none') ax_data.text(0.05, 0.95, datastr, transform=ax_data.transAxes, fontsize=14, verticalalignment='top', bbox=boxprops) # Logos ax_png = fignum.add_subplot(gs[3, 3]) img = mpimg.imread(logoName) plt.axis('off') plt.imshow(img) else: # Logos ax_png = fignum.add_subplot(gs[3, 2:]) img = mpimg.imread(logoName) plt.axis('off') plt.imshow(img) plt.show(block=False) return
def main(): img_dir = Path("hail_plots/soundings/") if not img_dir.exists(): img_dir.mkdir(parents=True) data_dir = Path("/HOME/huziy/skynet3_rech1/hail/soundings_from_erai/") # dates = [datetime(1991, 9, 7), datetime(1991, 9, 7, 6), datetime(1991, 9, 7, 12), datetime(1991, 9, 7, 18), # datetime(1991, 9, 8, 0), datetime(1991, 9, 8, 18)] # # dates.extend([datetime(1991, 9, 6, 0), datetime(1991, 9, 6, 6), datetime(1991, 9, 6, 12), datetime(1991, 9, 6, 18)]) # # dates = [datetime(1990, 7, 7), datetime(2010, 7, 12), datetime(1991, 9, 8, 0)] dates_s = """ - 07/09/1991 12:00 - 07/09/1991 18:00 - 08/09/1991 00:00 - 08/09/1991 06:00 - 08/09/1991 12:00 - 13/09/1991 12:00 - 13/09/1991 18:00 - 14/09/1991 00:00 - 14/09/1991 06:00 - 14/09/1991 12:00 """ dates = [datetime.strptime(line.strip()[1:].strip(), "%d/%m/%Y %H:%M") for line in dates_s.split("\n") if line.strip() != ""] def __date_parser(s): return pd.datetime.strptime(s, '%Y-%m-%d %H:%M:%S') tt = pd.read_csv(data_dir.joinpath("TT.csv"), index_col=0, parse_dates=['Time']) uu = pd.read_csv(data_dir.joinpath("UU.csv"), index_col=0, parse_dates=['Time']) vv = pd.read_csv(data_dir.joinpath("VV.csv"), index_col=0, parse_dates=['Time']) hu = pd.read_csv(data_dir.joinpath("HU.csv"), index_col=0, parse_dates=['Time']) print(tt.head()) print([c for c in tt]) print(list(tt.columns.values)) temp_perturbation_degc = 0 for the_date in dates: p = np.array([float(c) for c in tt]) fig = plt.figure(figsize=(9, 9)) skew = SkewT(fig) skew.ax.set_ylim(1000, 100) skew.ax.set_xlim(-40, 60) tsel = tt.select(lambda d: d == the_date) usel = uu.select(lambda d: d == the_date) vsel = vv.select(lambda d: d == the_date) husel = hu.select(lambda d: d == the_date) tvals = tsel.values.mean(axis=0) uvals = usel.values.mean(axis=0) * mul_mpers_per_knot vvals = vsel.values.mean(axis=0) * mul_mpers_per_knot huvals = husel.values.mean(axis=0) * units("g/kg") # ignore the lowest level all_vars = [p, tvals, uvals, vvals, huvals] for i in range(len(all_vars)): all_vars[i] = all_vars[i][:-5] p, tvals, uvals, vvals, huvals = all_vars assert len(p) == len(huvals) tdvals = calc.dewpoint(calc.vapor_pressure(p * units.mbar, huvals).to(units.mbar)) print(tvals, tdvals) # Calculate full parcel profile and add to plot as black line parcel_profile = calc.parcel_profile(p[::-1] * units.mbar, (tvals[-1] + temp_perturbation_degc) * units.degC, tdvals[-1]).to('degC') parcel_profile = parcel_profile[::-1] skew.plot(p, parcel_profile, 'k', linewidth=2) # Example of coloring area between profiles greater = tvals * units.degC >= parcel_profile skew.ax.fill_betweenx(p, tvals, parcel_profile, where=greater, facecolor='blue', alpha=0.4) skew.ax.fill_betweenx(p, tvals, parcel_profile, where=~greater, facecolor='red', alpha=0.4) skew.plot(p, tvals, "r") skew.plot(p, tdvals, "g") skew.plot_barbs(p, uvals, vvals) # Plot a zero degree isotherm l = skew.ax.axvline(0, color='c', linestyle='--', linewidth=2) # Add the relevant special lines skew.plot_dry_adiabats() skew.plot_moist_adiabats() skew.plot_mixing_lines() plt.title("{} (dT={})".format(the_date, temp_perturbation_degc)) img_path = "{}_dT={}.png".format(the_date.strftime("%Y%m%d_%H%M%S"), temp_perturbation_degc) img_path = img_dir.joinpath(img_path) fig.savefig(str(img_path), bbox_inches="tight") plt.close(fig)
def draw_sta_skewT(p=None, T=None, Td=None, wind_speed=None, wind_dir=None, u=None, v=None, fcst_info=None, output_dir=None): fig = plt.figure(figsize=(9, 9)) skew = SkewT(fig, rotation=45) plt.rcParams['font.sans-serif'] = ['SimHei'] # 步骤一(替换sans-serif字体) plt.rcParams['axes.unicode_minus'] = False # 步骤二(解决坐标轴负数的负号显示问题) # Plot the data using normal plotting functions, in this case using # log scaling in Y, as dictated by the typical meteorological plot. skew.plot(p, T, 'r') skew.plot(p, Td, 'g') skew.plot_barbs(p, u, v) skew.ax.set_ylim(1000, 100) skew.ax.set_xlim(-40, 60) # Calculate LCL height and plot as black dot. Because `p`'s first value is # ~1000 mb and its last value is ~250 mb, the `0` index is selected for # `p`, `T`, and `Td` to lift the parcel from the surface. If `p` was inverted, # i.e. start from low value, 250 mb, to a high value, 1000 mb, the `-1` index # should be selected. lcl_pressure, lcl_temperature = mpcalc.lcl(p[0], T[0], Td[0]) skew.plot(lcl_pressure, lcl_temperature, 'ko', markerfacecolor='black') # Calculate full parcel profile and add to plot as black line prof = mpcalc.parcel_profile(p, T[0], Td[0]).to('degC') skew.plot(p, prof, 'k', linewidth=2) # Shade areas of CAPE and CIN skew.shade_cin(p, T, prof) skew.shade_cape(p, T, prof) # An example of a slanted line at constant T -- in this case the 0 # isotherm skew.ax.axvline(0, color='c', linestyle='--', linewidth=2) # Add the relevant special lines skew.plot_dry_adiabats() skew.plot_moist_adiabats() skew.plot_mixing_lines() #forecast information bax = plt.axes([0.12, 0.88, .25, .07], facecolor='#FFFFFFCC') bax.axis('off') bax.axis([0, 10, 0, 10]) initTime = pd.to_datetime(str( fcst_info['forecast_reference_time'].values)).replace( tzinfo=None).to_pydatetime() if (sys.platform[0:3] == 'lin'): locale.setlocale(locale.LC_CTYPE, 'zh_CN.utf8') if (sys.platform[0:3] == 'win'): locale.setlocale(locale.LC_CTYPE, 'chinese') plt.text(2.5, 7.5, '起报时间: ' + initTime.strftime("%Y年%m月%d日%H时"), size=11) plt.text(2.5, 5.0, '[' + str(fcst_info.attrs['model']) + '] ' + str(int(fcst_info['forecast_period'].values[0])) + '小时预报探空', size=11) plt.text(2.5, 2.5, '预报点: ' + str(fcst_info.attrs['points']['lon']) + ', ' + str(fcst_info.attrs['points']['lat']), size=11) plt.text(2.5, 0.5, 'www.nmc.cn', size=11) utl.add_logo_extra_in_axes(pos=[0.1, 0.88, .07, .07], which='nmc', size='Xlarge') # Show the plot if (output_dir != None): plt.savefig( output_dir + '时间剖面产品_起报时间_' + str(fcst_info['forecast_reference_time'].values)[0:13] + '_预报时效_' + str(int(fcst_info.attrs['forecast_period'].values)) + '.png', dpi=200, bbox_inches='tight') else: plt.show()
T = df_selected_time['temperature'].values * units.degC Td = df_selected_time['dewpoint'].values * units.degC wind_speed = df_selected_time['speed'].values * units.knots wind_dir = df_selected_time['direction'].values * units.degrees u, v = mpcalc.wind_components(wind_speed, wind_dir) ########################################### # Create a new figure. The dimensions here give a good aspect ratio. fig = plt.figure(figsize=(9, 9)) #add_metpy_logo(fig, 115, 100) skew = SkewT(fig, rotation=45) # Plot the data using normal plotting functions, in this case using # log scaling in Y, as dictated by the typical meteorological plot skew.plot(p, T, 'r') skew.plot(p, T, 'ro', markersize=8, fillstyle='none') skew.plot(p, Td, 'g', linestyle='--') skew.plot(p, Td, 'g^', markersize=8, fillstyle='none') skew.plot_barbs(p, u, v) skew.ax.set_ylim(1050, 100) skew.ax.set_xlim(-50, 60) # Calculate LCL height and plot as black dot lcl_pressure, lcl_temperature = mpcalc.lcl(p[0], T[0], Td[0]) skew.plot(lcl_pressure, lcl_temperature, 'ko', markerfacecolor='black') #calculate potentional temperature #mpcalc.potential_temperature(p[0], T[0])
wspd=wspd, wdir=wdir, latitude=latitude, longitude=longitude, strictQC=True) #### Adding a Parcel Trace sfcpcl = params.parcelx(prof, flag=1) # Surface Parcel #fcstpcl = params.parcelx( prof, flag=2 ) # Forecast Parcel mupcl = params.parcelx(prof, flag=3) # Most-Unstable Parcel mlpcl = params.parcelx(prof, flag=4) # 100 mb Mean Layer Parcel # Set the parcel trace to be plotted as the Most-Unstable parcel. pcl = mupcl # Temperature, dewpoint, virtual temperature, wetbulb, parcel profiles temperature_trace, = skew.plot(prof.pres, prof.tmpc, 'r', linewidth=2) # temperature profile # annotate temperature in F at bottom of T profile temperatureF = skew.ax.text(prof.tmpc[0], prof.pres[0] + 10, utils.INT2STR(thermo.ctof(prof.tmpc[0])), verticalalignment='top', horizontalalignment='center', size=7, color=temperature_trace.get_color()) vtemp_trace, = skew.plot(prof.pres, prof.vtmp, 'r', linewidth=0.5) # Virtual temperature profile wetbulb_trace, = skew.plot(prof.pres, prof.wetbulb, 'c-') # wetbulb profile dewpoint_trace, = skew.plot(prof.pres, prof.dwpc, 'g', linewidth=2) # dewpoint profile # annotate dewpoint in F at bottom of dewpoint profile
def core_ens(p, T, Td, u, v, p2, T2, Td2, **kwargs): #from IPython import embed; embed() T = T.to(units.K) Td = Td.to(units.K) Tmean = T.mean(axis=0) Tdmean = Td.mean(axis=0) pmean = p.mean(axis=0) umean, vmean = u.mean(axis=0), v.mean(axis=0) Tstd = np.std(T.data, axis=0) * units.K Tdstd = np.std(Td.data, axis=0) * units.K # Calculate the parcel profile. parcel_prof = mpcalc.parcel_profile(pmean, Tmean[0], Tdmean[0]).to('degC') # Create a new figure. The dimensions here give a good aspect ratio fig = plt.figure(figsize=(8, 8)) skew = SkewT(fig, rotation=45) # Plot a zero degree isotherm skew.ax.axvline(0, color='k', linestyle='--', linewidth=1) # Add the relevant special lines skew.plot_dry_adiabats(lw=.5) skew.plot_moist_adiabats(lw=.5) skew.plot_mixing_lines(lw=.5) # Plot the data using normal plotting functions, in this case using # log scaling in Y, as dictated by the typical meteorological plot skew.shade_area(pmean, Tmean - Tstd, Tmean + Tstd, color='r', label='std$_{ens}$ mean$_{dom}$ T$_{fc}$') skew.shade_area(pmean, Tdmean - Tdstd, Tdmean + Tdstd, color='g', label='std$_{ens}$ mean$_{dom}$ Td$_{fc}$') #skew.plot(p, Tmean+np.std(T), '-', color='grey', lw=1, label='p.999(T)') skew.plot(pmean, Tmean, 'r:', ms=3, lw=1, label='mean$_{ens, dom}$ T$_{fc}$') skew.plot(pmean, Tdmean, 'g:', ms=3, lw=1, label='mean$_{ens, dom}$ Td$_{fc}$') skew.plot_barbs(pmean, umean, vmean) # Plot the parcel profile as a black line skew.plot(pmean, parcel_prof, 'k', linewidth=.5) # Shade areas of CAPE and CIN skew.shade_cin(pmean, Tmean, parcel_prof, alpha=0.2) skew.shade_cape(pmean, Tmean, parcel_prof, alpha=0.2) # nature skew.plot(p2, T2, 'r.-', ms=5, lw=2, label='mean$_{ens, dom}$ T$_{nature}$') skew.plot(p2, Td2, 'g.-', ms=5, lw=2, label='mean$_{ens, dom}$ Td$_{nature}$') skew.ax.set_ylim(1000, 180) skew.ax.set_xlim(-20, 40) plt.legend(loc='lower left') plt.title(kwargs.get('title')) fname = kwargs.get('saveto', 'profile.png') fig.savefig(fname) print(fname, 'saved.') plt.close()
from metpy.calc import get_wind_components, lcl, dry_lapse, parcel_profile from metpy.plots import SkewT # Parse the data p, T, Td, direc, spd = np.loadtxt('../testdata/may3_sounding.txt', usecols=(0, 2, 3, 6, 7), unpack=True) u,v = get_wind_components(spd, direc) # Create a new figure. The dimensions here give a good aspect ratio fig = plt.figure(figsize=(9, 9)) skew = SkewT(fig, rotation=45) # Plot the data using normal plotting functions, in this case using # log scaling in Y, as dictated by the typical meteorological plot skew.plot(p, T, 'r') skew.plot(p, Td, 'g') skew.plot_barbs(p, u, v) skew.ax.set_ylim(1000, 100) skew.ax.set_xlim(-40, 60) # Calculate LCL height and plot as black dot l = lcl(p[0], C2K(T[0]), C2K(Td[0])) skew.plot(l, K2C(dry_lapse(l, C2K(T[0]), p[0])), 'ko', markerfacecolor='black') # Calculate full parcel profile and add to plot as black line prof = K2C(parcel_profile(p, C2K(T[0]), C2K(Td[0]))) skew.plot(p, prof, 'k', linewidth=2) # Example of coloring area between profiles
########################################### # Create a new figure. The dimensions here give a good aspect ratio. fig = plt.figure(figsize=(28, 24)) #add_metpy_logo(fig, 115, 100) skew = SkewT(fig, rotation=45) skew.ax.set_title('skew T log p diagram\n', fontsize=30) skew.ax.set_xlabel(r'temperature ($ \degree C$)', fontsize=24) skew.ax.set_ylabel(r'pressure ($ hPa $)', fontsize=24) # Plot the data using normal plotting functions, in this case using # log scaling in Y, as dictated by the typical meteorological plot #skew.plot(p, T, 'r') skew.plot(p, T, 'ro', markersize = 0, fillstyle='none', label='temperature') #skew.plot(p, Td, 'g', linestyle='--') skew.plot(p, Td, 'g^', markersize = 0, fillstyle='none', label='dew point temperature') #skew.plot_barbs(p, u, v) skew.ax.set_ylim(yylim[0], yylim[1]) skew.ax.set_xlim(xxlim[0], xxlim[1]) skew.ax.tick_params(axis="x", labelsize=14, pad=10, rotation=45, labelcolor='brown') skew.ax.tick_params(axis="y", labelsize=14, pad=0.5) # Calculate full parcel profile and add to plot as black line #prof_0 = mpcalc.parcel_profile(p, T[0], Td[0]).to('degC') #skew.plot(p, prof_0, 'k', linewidth=1.5) # Shade areas of CAPE and CIN '''
#fig, ax = plt.subplots(figsize = (5,12)) #ax.plot(RH_RA[1:len(RH_RA)-1], z_RA[1:len(z_RA)-1], color = 'red', zorder = 5) #ax.plot(RH_RS, z_RS, color = 'black') #ax.set_title(Time_RA, fontsize = 16) #ax.set_ylim(0,10000) #ax.set_ylabel('Altitude [m]', fontsize = 16) #ax.set_xlabel('RH [%]', fontsize = 16) #ax.tick_params(labelsize = 16) fig = plt.figure(figsize=(9, 9)) skew = SkewT(fig) ######################################### ##### A) SMN: Surface measurement ######################################### skew.plot(pressure_SMN, temperature_SMN, 'ro', color='orange', label='surf T') skew.plot(pressure_SMN, temperature_d_SMN, 'bo', color='orange', label='surf Td') ########################################## ##### B) RS: RADIOSONDE ########################################## # original RS data skew.plot(p_RS_original, T_RS_original, color='red', linewidth=2, label='RS T') skew.plot(p_RS_original, T_d_RS_original, color='red', linewidth=2,
with UseSampleData(): # Only needed to use our local sample data # Download and parse the data dataset = get_upper_air_data(datetime(2013, 1, 20, 12), 'OUN') p = dataset.variables['pressure'][:] T = dataset.variables['temperature'][:] Td = dataset.variables['dewpoint'][:] u = dataset.variables['u_wind'][:] v = dataset.variables['v_wind'][:] ########################################### skew = SkewT() # Plot the data using normal plotting functions, in this case using # log scaling in Y, as dictated by the typical meteorological plot skew.plot(p, T, 'r') skew.plot(p, Td, 'g') skew.plot_barbs(p, u, v) # Add the relevant special lines skew.plot_dry_adiabats() skew.plot_moist_adiabats() skew.plot_mixing_lines() skew.ax.set_ylim(1000, 100) ########################################### # Example of defining your own vertical barb spacing skew = SkewT() # Plot the data using normal plotting functions, in this case using
def plot_upper_air(station='11035', date=False): ''' ----------------------------- Default use of plot_upper_air: This will plot a SkewT sounding for station '11035' (Wien Hohe Warte) plot_upper_air(station='11035', date=False) ''' # sns.set(rc={'axes.facecolor':'#343837', 'figure.facecolor':'#343837', # 'grid.linestyle':'','axes.labelcolor':'#04d8b2','text.color':'#04d8b2', # 'xtick.color':'#04d8b2','ytick.color':'#04d8b2'}) # Get time in UTC station = str(station) if date is False: now = datetime.utcnow() # If morning then 0z sounding, otherwise 12z if now.hour < 12: hour = 0 else: hour = 12 date = datetime(now.year, now.month, now.day, hour) datestr = date.strftime('%Hz %Y-%m-%d') print('{}'.format(date)) else: year = int(input('Please specify the year: ')) month = int(input('Please specify the month: ')) day = int(input('Please specify the day: ')) hour = int(input('Please specify the hour: ')) if hour < 12: hour = 0 else: hour = 12 date = datetime(year, month, day, hour) datestr = date.strftime('%Hz %Y-%m-%d') print('You entered {}'.format(date)) # This requests the data 11035 is df = WyomingUpperAir.request_data(date, station) # Create single variables wih the right units p = df['pressure'].values * units.hPa T = df['temperature'].values * units.degC Td = df['dewpoint'].values * units.degC wind_speed = df['speed'].values * units.knots wind_dir = df['direction'].values * units.degrees wind_speed_6k = df['speed'][df.height <= 6000].values * units.knots wind_dir_6k = df['direction'][df.height <= 6000].values * units.degrees u, v = mpcalc.get_wind_components(wind_speed, wind_dir) u6, v6 = mpcalc.get_wind_components(wind_speed_6k, wind_dir_6k) # Calculate the LCL lcl_pressure, lcl_temperature = mpcalc.lcl(p[0], T[0], Td[0]) print(lcl_pressure, lcl_temperature) # Calculate the parcel profile. parcel_prof = mpcalc.parcel_profile(p, T[0], Td[0]).to('degC') cape, cin = mpcalc.cape_cin(p, T, Td, parcel_prof) ############################# # Create a new figure. The dimensions here give a good aspect ratio fig = plt.figure(figsize=(9, 9)) gs = gridspec.GridSpec(3, 3) skew = SkewT(fig, rotation=45, subplot=gs[:, :2]) # Plot the data using normal plotting functions, in this case using # log scaling in Y, as dictated by the typical meteorological plot skew.plot(p, T, 'r') skew.plot(p, Td, 'g') skew.plot_barbs(p, u, v) skew.ax.set_ylim(1000, 100) skew.ax.set_xlim(-45, 40) # Plot LCL as black dot skew.plot(lcl_pressure, lcl_temperature, 'ko', markerfacecolor='black') # Plot the parcel profile as a black line skew.plot(p, parcel_prof, 'k', linewidth=2) # Shade areas of CAPE and CIN skew.shade_cin(p, T, parcel_prof) skew.shade_cape(p, T, parcel_prof) # Plot a zero degree isotherm skew.ax.axvline(0, color='c', linestyle='--', linewidth=2) skew.ax.set_title('Station: ' + str(station) + '\n' + datestr) # set title skew.ax.set_xlabel('Temperature (C)') skew.ax.set_ylabel('Pressure (hPa)') # Add the relevant special lines skew.plot_dry_adiabats(linewidth=0.7) skew.plot_moist_adiabats(linewidth=0.7) skew.plot_mixing_lines(linewidth=0.7) # Create a hodograph # Create an inset axes object that is 40% width and height of the # figure and put it in the upper right hand corner. # ax_hod = inset_axes(skew.ax, '40%', '40%', loc=1) ax = fig.add_subplot(gs[0, -1]) h = Hodograph(ax, component_range=60.) h.add_grid(increment=20) # Plot a line colored by windspeed h.plot_colormapped(u6, v6, wind_speed_6k) # add another subplot for the text of the indices # ax_t = fig.add_subplot(gs[1:,2]) skew2 = SkewT(fig, rotation=0, subplot=gs[1:, 2]) skew2.plot(p, T, 'r') skew2.plot(p, Td, 'g') # skew2.plot_barbs(p, u, v) skew2.ax.set_ylim(1000, 700) skew2.ax.set_xlim(-30, 10) # Show the plot plt.show() return cape
print "no good data lines. empty profile" continue prof = profile.create_profile(profile='default', pres=pres, hght=hght, tmpc=tmpc, dwpc=dwpc, wspd=wspd, wdir=wdir, latitude=latitude, longitude=longitude, missing=-999., strictQC=True) #### Adding a Parcel Trace sfcpcl = params.parcelx( prof, flag=1 ) # Surface Parcel #fcstpcl = params.parcelx( prof, flag=2 ) # Forecast Parcel mupcl = params.parcelx( prof, flag=3 ) # Most-Unstable Parcel mlpcl = params.parcelx( prof, flag=4 ) # 100 mb Mean Layer Parcel # Set the parcel trace to be plotted as the Most-Unstable parcel. pcl = mupcl # Temperature, dewpoint, virtual temperature, wetbulb, parcel profiles temperature_trace, = skew.plot(prof.pres, prof.tmpc, 'r', linewidth=2) # temperature profile # annotate temperature in F at bottom of T profile temperatureF = skew.ax.text(prof.tmpc[0], prof.pres[0]+10, utils.INT2STR(thermo.ctof(prof.tmpc[0])), verticalalignment='top', horizontalalignment='center', size=7, color=temperature_trace.get_color()) skew.plot(prof.pres, prof.vtmp, 'r', linewidth=0.5) # Virtual temperature profile skew.plot(prof.pres, prof.wetbulb, 'c-') # wetbulb profile dwpt_trace, = skew.plot(prof.pres, prof.dwpc, 'g', linewidth=2) # dewpoint profile # annotate dewpoint in F at bottom of dewpoint profile dewpointF = skew.ax.text(prof.dwpc[0], prof.pres[0]+10, utils.INT2STR(thermo.ctof(prof.dwpc[0])), verticalalignment='top', horizontalalignment='center', size=7, color=dwpt_trace.get_color()) skew.plot(pcl.ptrace, pcl.ttrace, 'brown', linestyle="dashed" ) # parcel temperature trace skew.ax.set_ylim(1050,100) skew.ax.set_xlim(-50,45) # Plot the effective inflow layer using purple horizontal lines
########################################################################## # Skew-T Plotting # ------------------------ # # Fiducial lines indicating dry adiabats, moist adiabats, and mixing ratio are # useful when performing further analysis on the Skew-T diagram. Often the # 0C isotherm is emphasized and areas of CAPE and CIN are shaded. # Create a new figure. The dimensions here give a good aspect ratio fig = plt.figure(figsize=(9, 9)) skew = SkewT(fig, rotation=30) # Plot the data using normal plotting functions, in this case using # log scaling in Y, as dictated by the typical meteorological plot skew.plot(p, T, 'r') skew.plot(p, Td, 'g') skew.plot_barbs(p, u, v) skew.ax.set_ylim(1000, 100) skew.ax.set_xlim(-40, 60) skew.ax.set_xlabel('Temperature [°C]') skew.ax.set_ylabel('Pressure [hPa]') # Plot LCL temperature as black dot skew.plot(lcl_pressure, lcl_temperature, 'ko', markerfacecolor='black') # Plot the parcel profile as a black line skew.plot(p, parcel_prof, 'k', linewidth=2) # Shade areas of CAPE and CIN skew.shade_cin(p, T, parcel_prof)
def cape(filelist,storm,track,show): #Sort filelist. filelist=np.sort(filelist) # Get sampling periods (this will be a dictionary). See the toolbox print('Retrieving sampling periods') sampleperiods=getsamplingperiods(filelist,3.) # Iterate over all sampling periods. for sampindex,periodskey in enumerate(sampleperiods): #Allocate starting (stdt) and ending date (endt). Remeber dt is the convetional short-name for date. stdt=periodskey endt=sampleperiods[periodskey] # Define sampling period string period=str(stdt.hour)+'_'+str(stdt.day)+'-'+str(endt.hour)+'_'+str(endt.day) # Create new-empty lists. lats=[] lons=[] xs=[] ys=[] capes=[] cins=[] distfig = plt.figure(figsize=(13, 9)) ax=distfig.add_subplot(111) print('start filelist loop') # Iterate over all files. for filename in filelist: # Select end-name of file by inspecting filename string. Notice how filename can change how file is read. if 'radazm' in filename.split('/')[-1] or 'eol' in filename.split('/')[-1]: end='radazm' else: end='avp' # Obtain properties of file, i.e., launch time and location into a dictionary (dicc). dicc=findproperties(filename,end) # Condition to see if current file is in sampling period. # Notice how if structure is constructed, condition finds times outside of sampling period and # if found outside the sampling period, continue to next file. if dicc['Launch Time']<stdt or dicc['Launch Time'] > endt: continue nump=np.genfromtxt(filename,skip_header=16,skip_footer=0) temperature=clean1(nump[:,5]) pressure=clean1(nump[:,4]) Height=clean1(nump[:,13]) if np.nanmax(Height)<3500: continue #Clean for cape RelH=clean1(nump[:,7]) lon=clean1(nump[:,14]) lat=clean1(nump[:,15]) lon=clean1(lon) lat=clean1(lat) mlon=np.nanmean(lon) mlat=np.nanmean(lat) RH=RelH/100 T,P,rh,dz=cleanforcape(temperature,pressure,RH,Height) #Metpy set-up T=np.flip(T,0) rh=np.flip(rh,0) p=np.flip(P,0) dz=np.flip(dz,0) p=p*units.hPa T=T*units.celsius mixing=rh*mpcalc.saturation_mixing_ratio(p,T) epsilon=0.6219800858985514 Tv=mpcalc.virtual_temperature(T, mixing, molecular_weight_ratio=epsilon) dwpoint=mpcalc.dewpoint_rh(T, rh) blh_indx=np.where(dz<500) try: parcelprofile=mpcalc.parcel_profile(p,np.nanmean(T[blh_indx])*units.celsius,mpcalc.dewpoint_rh(np.nanmean(T[blh_indx])*units.celsius, np.nanmean(rh[blh_indx]))).to('degC') Tv_parcelprofile=mpcalc.virtual_temperature(parcelprofile, mixing, molecular_weight_ratio=epsilon) cape,cin=cape_cin(p,Tv,dwpoint,Tv_parcelprofile,dz,T) except: continue plotskewT=True if plotskewT==True: os.system('mkdir figs/skewt') fig = plt.figure(figsize=(9, 9)) skew = SkewT(fig, rotation=45) skew.ax.set_ylim(1000, 100) skew.ax.set_xlim(-40, 60) skew.plot(p, dwpoint, 'g',label=r'$T_{dp}$') skew.plot(p, Tv, 'r',label=r'$T_v$') plt.text(-120,120,str(np.around(cape,2)),fontsize=14,fontweight='bold') # Plot the data using normal plotting functions, in this case using # log scaling in Y, as dictated by the typical meteorological plot skew.plot(p,Tv_parcelprofile,'k',label=r'$T_{v env}$') skew.shade_cin(p, T, parcelprofile,label='CIN') skew.shade_cape(p, Tv, Tv_parcelprofile,label='CAPE') skew.plot_dry_adiabats() skew.plot_moist_adiabats() plt.legend() plt.title(storm + ' on' + period,fontsize=14) plt.savefig('figs/skewt/'+storm+str(dicc['Launch Time'].time())+'.png') #plt.show() plt.close() r,theta=cart_to_cylindr(mlon,mlat,track,dicc['Launch Time']) if not(np.isnan(r)) and not(np.isnan(theta)) and not(np.isnan(cape.magnitude)): xs.append(r*np.cos(theta)) ys.append(r*np.sin(theta)) capes.append(cape.magnitude) cins.append(cin) cs=ax.scatter(xs,ys,c=np.asarray(capes),cmap='jet') for i,xi in enumerate(xs): ax.text(xi,ys[i]+10,str(np.around(capes[i],1))) plt.colorbar(cs) ax.scatter(0,0,marker='v',s=100,color='black') ax.grid() ax.set_xlabel('X distance [km]') ax.set_ylabel('Y distance [km]') ax.set_title('CAPE distribution for '+storm+' on '+period,fontsize=14) distfig.savefig('figs/cape'+storm+period+'.png') if show: plt.show()
p = df['pressure'].values * units.hPa T = df['temperature'].values * units.degC Td = df['dewpoint'].values * units.degC u = df['Uwind'].values * units.meter / (units.second) v = df['Vwind'].values * units.meter / (units.second) # lcl_pressure, lcl_temperature = mpcalc.lcl(p[0], T[0], Td[0]) # parcel_prof = mpcalc.parcel_profile(p, T[0], Td[0]).to('degC') fig = plt.figure(figsize=(11, 8.5)) skew = SkewT(fig, rotation=45) # Plot the data using normal plotting functions, in this case using # log scaling in Y, as dictated by the typical meteorological plot skew.plot(p, T, 'r', linewidth=3) skew.plot(p, Td, 'g', linewidth=3) skew.plot_barbs(p[::100], u[::100], v[::100]) skew.ax.set_ylim(1020, 300) skew.ax.set_xlim(-20, 40) skew.ax.tick_params(labelsize=24.) skew.ax.set_xlabel('temperature ($\degree C$)', linespacing=7, fontsize=24.) skew.ax.set_ylabel('pressure ($hPa$)', linespacing=4, fontsize=24.) skew.ax.set_title('Skew-T Log-P Diagram' + '\n' + '$_{station:}$ $_{' + station + '}$' ' $_{local}$ $_{time:}$ $_{' + file[i][29:33] + '/' + file[i][33:35] + '/' + file[i][35:37] + '}$' + ' $_{' + file[i][37:39] + ':00}$', verticalalignment='bottom',
wind_speed = df['speed'].values * units.knots wind_dir = df['direction'].values * units.degrees u, v = mpcalc.get_wind_components(wind_speed, wind_dir) ########################################### # Create a new figure. The dimensions here give a good aspect ratio fig = plt.figure(figsize=(9, 9)) add_metpy_logo(fig, 115, 100) # Grid for plots skew = SkewT(fig, rotation=45) # Plot the data using normal plotting functions, in this case using # log scaling in Y, as dictated by the typical meteorological plot skew.plot(p, T, 'r') skew.plot(p, Td, 'g') skew.plot_barbs(p, u, v) skew.ax.set_ylim(1000, 100) # Add the relevant special lines skew.plot_dry_adiabats() skew.plot_moist_adiabats() skew.plot_mixing_lines() # Good bounds for aspect ratio skew.ax.set_xlim(-50, 60) # Create a hodograph ax_hod = inset_axes(skew.ax, '40%', '40%', loc=1) h = Hodograph(ax_hod, component_range=80.)
u, v = mpcalc.wind_components(wind_speed, wind_dir) ########################################### # Create a new figure. The dimensions here give a good aspect ratio. fig = plt.figure(figsize=(28, 24)) #add_metpy_logo(fig, 115, 100) skew = SkewT(fig, rotation=45) skew.ax.set_title('skew T log p diagram\n', fontsize=30) skew.ax.set_xlabel(r'temperature ($ \degree C$)', fontsize=24) skew.ax.set_ylabel(r'pressure ($ hPa $)', fontsize=24) # Plot the data using normal plotting functions, in this case using # log scaling in Y, as dictated by the typical meteorological plot skew.plot(p, T, 'r') skew.plot(p, T, 'ro', markersize=8, fillstyle='none', label='temperature') skew.plot(p, Td, 'g', linestyle='--') skew.plot(p, Td, 'g^', markersize=8, fillstyle='none', label='dew point temperature') skew.plot_barbs(p, u, v)
class Window(QtGui.QMainWindow): r""" A mainwindow object for the GUI display. Inherits from QMainWindow.""" def __init__(self): super(Window, self).__init__() self.interface() def interface(self): r""" Contains the main window interface generation functionality. Commented where needed.""" # Get the screen width and height and set the main window to that size screen = QtGui.QDesktopWidget().screenGeometry() self.setGeometry(0, 0, 800, screen.height()) self.setMaximumSize(QtCore.QSize(800, 2000)) # Set the window title and icon self.setWindowTitle("WAVE: Weather Analysis and Visualization Environment") self.setWindowIcon(QtGui.QIcon('./img/wave_64px.png')) # Import the stylesheet for this window and set it to the window stylesheet = "css/MainWindow.css" with open(stylesheet, "r") as ssh: self.setStyleSheet(ssh.read()) self.setAutoFillBackground(True) self.setBackgroundRole(QtGui.QPalette.Highlight) # Create actions for menus and toolbar exit_action = QtGui.QAction(QtGui.QIcon('./img/exit_64px.png'), 'Exit', self) exit_action.setShortcut('Ctrl+Q') exit_action.setStatusTip('Exit application') exit_action.triggered.connect(self.close) clear_action = QtGui.QAction(QtGui.QIcon('./img/clear_64px.png'), 'Clear the display', self) clear_action.setShortcut('Ctrl+C') clear_action.setStatusTip('Clear the display') clear_action.triggered.connect(self.clear_canvas) skewt_action = QtGui.QAction(QtGui.QIcon('./img/skewt_64px.png'), 'Open the skew-T dialog', self) skewt_action.setShortcut('Ctrl+S') skewt_action.setStatusTip('Open the skew-T dialog') skewt_action.triggered.connect(self.skewt_dialog) radar_action = QtGui.QAction(QtGui.QIcon('./img/radar_64px.png'), 'Radar', self) radar_action.setShortcut('Ctrl+R') radar_action.setStatusTip('Open Radar Dialog Box') radar_action.triggered.connect(self.radar_dialog) # Create the top menubar, setting native to false (for OS) and add actions to the menus menubar = self.menuBar() menubar.setNativeMenuBar(False) filemenu = menubar.addMenu('&File') editmenu = menubar.addMenu('&Edit') helpmenu = menubar.addMenu('&Help') filemenu.addAction(exit_action) # Create the toolbar, place it on the left of the GUI and add actions to toolbar left_tb = QtGui.QToolBar() self.addToolBar(QtCore.Qt.LeftToolBarArea, left_tb) left_tb.setMovable(False) left_tb.addAction(clear_action) left_tb.addAction(skewt_action) left_tb.addAction(radar_action) self.setIconSize(QtCore.QSize(30, 30)) # Create the toolbar, place it on the left of the GUI and add actions to toolbar right_tb = QtGui.QToolBar() self.addToolBar(QtCore.Qt.RightToolBarArea, right_tb) right_tb.setMovable(False) right_tb.addAction(clear_action) right_tb.addAction(skewt_action) right_tb.addAction(radar_action) # Create the status bar with a default display self.statusBar().showMessage('Ready') # Figure and canvas widgets that display the figure in the GUI self.figure = plt.figure(facecolor='#2B2B2B') self.canvas = FigureCanvas(self.figure) # Add subclassed matplotlib navbar to GUI # spacer widgets for left and right of buttons left_spacer = QtGui.QWidget() left_spacer.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) right_spacer = QtGui.QWidget() right_spacer.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) self.mpltb = QtGui.QToolBar() self.mpltb.addWidget(left_spacer) self.mpltb.addWidget(MplToolbar(self.canvas, self)) self.mpltb.addWidget(right_spacer) self.mpltb.setMovable(False) self.addToolBar(QtCore.Qt.TopToolBarArea, self.mpltb) # Set the figure as the central widget and show the GUI self.setCentralWidget(self.canvas) self.show() def skewt_dialog(self): r""" When the toolbar icon for the Skew-T dialog is clicked, this function is executed. Creates an instance of the SkewTDialog object which is the dialog box. If the submit button on the dialog is clicked, get the user inputted values and pass them into the sounding retrieval call (DataAccessor.get_sounding) to fetch the data. Finally, plot the returned data via self.plot. Args: None. Returns: None. Raises: None. """ dialog = SkewTDialog() if dialog.exec_(): source, lat, long = dialog.get_values() t, td, p, u, v, lat, long, time = DataAccessor.get_sounding(source, lat, long) self.plot(t, td, p, u, v, lat, long, time) def plot(self, t, td, p, u, v, lat, long, time): r"""Displays the Skew-T data on a matplotlib figure. Args: t (array-like): A list of temperature values. td (array-like): A list of dewpoint values. p (array-like): A list of pressure values. u (array-like): A list of u-wind component values. v (array-like): A list of v-wind component values. lat (string): A string containing the requested latitude value. long (string): A string containing the requested longitude value. time (string): A string containing the UTC time requested with seconds truncated. Returns: None. Raises: None. """ # Create a new figure. The dimensions here give a good aspect ratio self.skew = SkewT(self.figure, rotation=40) # Plot the data using normal plotting functions, in this case using # log scaling in Y, as dictated by the typical meteorological plot self.skew.plot(p, t, 'r') self.skew.plot(p, td, 'g') self.skew.plot_barbs(p, u, v, barbcolor='#FF0000', flagcolor='#FF0000') self.skew.ax.set_ylim(1000, 100) self.skew.ax.set_xlim(-40, 60) # Axis colors self.skew.ax.tick_params(axis='x', colors='#A3A3A4') self.skew.ax.tick_params(axis='y', colors='#A3A3A4') # Calculate LCL height and plot as black dot l = lcl(p[0], t[0], td[0]) lcl_temp = dry_lapse(concatenate((p[0], l)), t[0])[-1].to('degC') self.skew.plot(l, lcl_temp, 'ko', markerfacecolor='black') # Calculate full parcel profile and add to plot as black line prof = parcel_profile(p, t[0], td[0]).to('degC') self.skew.plot(p, prof, 'k', linewidth=2) # Color shade areas between profiles self.skew.ax.fill_betweenx(p, t, prof, where=t >= prof, facecolor='#5D8C53', alpha=0.7) self.skew.ax.fill_betweenx(p, t, prof, where=t < prof, facecolor='#CD6659', alpha=0.7) # Add the relevant special lines self.skew.plot_dry_adiabats() self.skew.plot_moist_adiabats() self.skew.plot_mixing_lines() # Set title deg = u'\N{DEGREE SIGN}' self.skew.ax.set_title('Sounding for ' + lat + deg + ', ' + long + deg + ' at ' + time + 'z', y=1.02, color='#A3A3A4') # Discards old graph, works poorly though # skew.ax.hold(False) # Figure and canvas widgets that display the figure in the GUI # set canvas size to display Skew-T appropriately self.canvas.setMaximumSize(QtCore.QSize(800, 2000)) # refresh canvas self.canvas.draw() def radar_dialog(self): r""" When the toolbar icon for the Skew-T dialog is clicked, this function is executed. Creates an instance of the SkewTDialog object which is the dialog box. If the submit button on the dialog is clicked, get the user inputted values and pass them into the sounding retrieval call (DataAccessor.get_sounding) to fetch the data. Finally, plot the returned data via self.plot. Args: None. Returns: None. Raises: None. """ radar_dialog = RadarDialog() if radar_dialog.exec_(): station, product = radar_dialog.get_radarvals() x, y, ref = DataAccessor.get_radar(station, product) self.plot_radar(x, y, ref) def plot_radar(self, x, y, ref): r"""Displays the Skew-T data on a matplotlib figure. Args: t (array-like): A list of temperature values. td (array-like): A list of dewpoint values. p (array-like): A list of pressure values. u (array-like): A list of u-wind component values. v (array-like): A list of v-wind component values. lat (string): A string containing the requested latitude value. long (string): A string containing the requested longitude value. time (string): A string containing the UTC time requested with seconds truncated. Returns: None. Raises: None. """ self.ax = self.figure.add_subplot(111) self.ax.pcolormesh(x, y, ref) self.ax.set_aspect('equal', 'datalim') self.ax.set_xlim(-460, 460) self.ax.set_ylim(-460, 460) self.ax.tick_params(axis='x', colors='#A3A3A4') self.ax.tick_params(axis='y', colors='#A3A3A4') # set canvas size to display Skew-T appropriately self.canvas.setMaximumSize(QtCore.QSize(800, 2000)) # refresh canvas self.canvas.draw() def clear_canvas(self): self.canvas.close() self.figure = plt.figure(facecolor='#2B2B2B') self.canvas = FigureCanvas(self.figure) self.setCentralWidget(self.canvas)
def skewt(self, ranges='Range', temp='Temperature', dewpoint=None, rel_hum='Relative Humidity', temp_units='K', wind=None, **kwargs): from metpy.plots import SkewT if not 'col' in kwargs.keys() and not 'row' in kwargs.keys(): # get unused dimensions unused = list(self._obj[temp].dims) if ranges in unused: unused.remove(ranges) # convert range (m) to hectopascals hpascals = 1013.25 * np.exp(-self._obj.coords[ranges] / 7) # return hpascals #return hpascals # convert temperature from Kelvins to Celsius #tempC = self._obj[temp] - 273.15 if temp_units == 'K': tempK = self._obj[temp].drop(unused) tempC = tempK - 273.15 else: tempC = self._obj[temp].drop(unused) tempK = tempC + 273.15 if dewpoint is None: # estimate dewpoint from relative humidity dewpoints = tempK - ((100 - self._obj[rel_hum].drop(unused)) / 5) - 273.15 else: dewpoints = self._obj[dewpoint].drop(unused) skew = SkewT() #return tempC skew.plot(hpascals, tempC, 'r') skew.plot(hpascals, dewpoints, 'g') skew.plot_dry_adiabats() skew.plot_moist_adiabats() if not wind is None: u = self._obj[wind].sel(Component='x').drop(unused) v = self._obj[wind].sel(Component='y').drop(unused) skew.plot_barbs(hpascals, u, v, xloc=.9) # skew.plot_mixing_lines() # skew.ax.set_ylim(1100, 100) else: if not wind is None: skewtdat = xr.concat([self._obj['Temperature'], self._obj['Relative Humidity'], self._obj[wind].sel(Component='x').drop('Component'), self._obj[wind].sel(Component='y').drop('Component')], 'measure') skewtdat.coords['measure'] = ['Temperature', 'Relative Humidity', 'windx', 'windy'] else: skewtdat = xr.concat([self._obj['Temperature'], self._obj['Relative Humidity']], 'measure') skewtdat.coords['measure'] = ['Temperature', 'Relative Humidity'] # skewtdat sk1 = xr.plot.FacetGrid(skewtdat, **kwargs) #return sk1 # need to make the subplot tuples for ax in sk1.axes.flat: ax.axis('off') #return sk1.axes.flat #return len(sk1.axes.flat) splots = range(len(sk1.axes.flat)) #return splots splot_dims = sk1.axes.shape splot_tuples = [] for i in splots: splot_tuples.append((splot_dims[0], splot_dims[1], i + 1)) if not wind is None: sk1.map(rasp.skewt, [0, 1, 2, 3], splots=splot_tuples, ranges=skewtdat.coords['Range'].values) else: sk1.map(rasp.skewt, [0, 1], splots=splot_tuples, ranges=skewtdat.coords['Range'].values)
# Create a new figure. The dimensions here give a good aspect ratio fig = plt.figure(figsize=(9, 9)) skew = SkewT(fig, rotation=30) # Plot the data using normal plotting functions, in this case using # log scaling in Y, as dictated by the typical meteorological plot #skew.plot(p, T, 'r') #skew.plot(p, Td, 'g') #skew.plot_barbs(p, u, v) skew.ax.set_ylim(1000, 100) skew.ax.set_xlim(-40, 60) # Plot LCL temperature as black dot skew.plot(lcl_pressure, lcl_temperature, 'ko', markerfacecolor='black', alpha=0) #alpha = 0 make dot transparents ## Plot the parcel profile as a black line #skew.plot(p, parcel_prof, 'k', linewidth=2) # ## Shade areas of CAPE and CIN ##skew.shade_cin(p, T, parcel_prof, Td) #skew.shade_cape(p, T, parcel_prof) # ## Plot a zero degree isotherm #skew.ax.axvline(0, color='c', linestyle='--', linewidth=2) # Add the relevant special lines skew.plot_dry_adiabats()
'size': 10, } font_title = { 'family': 'monospace', 'color': 'black', 'weight': 'normal', 'size': 20, } font_axis = { 'family': 'monospace', 'color': 'black', 'weight': 'normal', 'size': 10, } skew.plot(p_year1, T_year1, 'k', linewidth=2) skew.plot(pd_year1, Td_year1, 'k-.', alpha=0.8) skew.plot(p, Temp_y1_to_y2, 'r', linewidth=2) skew.plot(p, Td_y1_to_y2, 'r-.', alpha=0.8) skew.plot(p, T_min, 'r:', alpha=0.8) skew.plot(p, T_max, 'r:', alpha=0.8) skew.ax.set_ylim(1000, 100) skew.ax.set_xlim(-30, 60) if stationid == "FIM00002963" or stationid == "FIM00002836": title = station + " " + time + "UTC month=" + month + " (NOAA)" else: title = stationid + " " + time + "UTC month=" + month + " (NOAA)" plt.title(title, fontdict=font_title) plt.xlabel("T (C)", fontdict=font_axis)
T = data['temperature'] Td = data['dewpoint'] u = data['u_wind'] v = data['v_wind'] # The code below makes a basic skew-T plot using the MetPy plot module that contains a SkewT class. # Change default to be better for skew-T fig = plt.figure(figsize=(9, 11)) # Initiate the skew-T plot type from MetPy class loaded earlier skew = SkewT(fig, rotation=45) # Plot the data using normal plotting functions, in this case using # log scaling in Y, as dictated by the typical meteorological plot skew.plot(p, T, 'r') skew.plot(p, Td, 'b') skew.plot_barbs(p[::3], u[::3], v[::3], y_clip_radius=0.03, flip_barb=True) # Set some appropriate axes limits for x and y skew.ax.set_xlim(-40, 40) skew.ax.set_ylim(860, 100) # Add the relevant special lines to plot throughout the figure skew.plot_dry_adiabats(t0=np.arange(233, 533, 10) * units.K, alpha=0.25, color='orangered') skew.plot_moist_adiabats(t0=np.arange(233, 400, 5) * units.K, alpha=0.25, color='tab:green') skew.plot_mixing_lines(p=np.arange(1000, 99, -20) * units.hPa,
# Convert wind speed and direction to components from metpy.calc import get_wind_components u, v = get_wind_components(spd, direc) ################## PLOTTING ON A SKEW-T logP ###################### import matplotlib.pyplot as plt from metpy.plots import SkewT # create a new figure. The dimensions here gove a good aspect ratio fig = plt.figure(figsize=(7, 9)) skew = SkewT(fig) # passing the figure, use skewT # Plot the data using normal plotting functions, in this case using # log scaling in Y, as dictated by the typical meteorological plot skew.plot(p, T, 'r') # pressure and temperature in red skew.plot(p, Td, 'g') skew.plot_barbs(p, u, v) skew.ax.set_ylim(1000, 100) # Y limits from 1000 in the botton to 100 millibars to the top skew.ax.set_xlim(-40, 60) # X limits # Add the relevant special lines\n", skew.plot_dry_adiabats() skew.plot_moist_adiabats() skew.plot_mixing_lines() plt.show() # Calculate LCL height and plot as black dot\n", from metpy.calc import lcl, dry_lapse from metpy.units import units, concatenate
for i in range(0, 6): lat = startlat + lat_delts[i] sound_lats.append(lat) print(sound_lats) for i in range(1, r): soundlat = sound_lats[0] soundlon = 360 - (startlon + (londelt * i)) sound_temps = data["temperature"].interp(lat=soundlat, lon=soundlon) - 273.15 sound_rh = data["rh"].interp(lat=soundlat, lon=soundlon) sound_dp = mpcalc.dewpoint_from_relative_humidity( sound_temps.data * units.degC, sound_rh.data * units.percent ) skew = SkewT(fig=fig, rect=(0.75 - (0.15 * i), 0.2, 0.15, 0.1)) skew.plot(sound_pres, sound_dp, "g", linewidth=3) skew.plot(sound_pres, sound_temps, "r", linewidth=3) skew.ax.axvline(0, color="purple", linestyle="--", linewidth=3) skew.ax.set_ylim((1000, ptop)) skew.ax.axis("off") for i in range(0, r): soundlat = sound_lats[1] soundlon = 360 - (startlon + (londelt * i)) sound_temps = data["temperature"].interp(lat=soundlat, lon=soundlon) - 273.15 sound_rh = data["rh"].interp(lat=soundlat, lon=soundlon) sound_dp = mpcalc.dewpoint_from_relative_humidity( sound_temps.data * units.degC, sound_rh.data * units.percent )
u, v = mpcalc.wind_components(wind_speed, wind_dir) # Create a new figure. The dimensions here give a good aspect ratio. fig = plt.figure(figsize=(15, 20)) #add_metpy_logo(fig, 115, 100) skew = SkewT(fig, rotation=45) skew.ax.set_title('skew T log p diagram\n', fontsize=24) skew.ax.set_xlabel('temperature ($ \degree C$)', fontsize=18) skew.ax.set_ylabel('pressure ($ hPa $)', fontsize=18) # Plot the data using normal plotting functions, in this case using # log scaling in Y, as dictated by the typical meteorological plot #skew.plot(p, T, 'r') #skew.plot(p, T, 'ro', markersize = 8, fillstyle='none', label='temperature') skew.plot(p, T, 'ro', markersize = 0.1, fillstyle='none') #skew.plot(p, Td, 'g', linestyle='--') #skew.plot(p, Td, 'g^', markersize = 8, fillstyle='none', label='dew point temperature') #skew.plot_barbs(p, u, v) skew.ax.set_ylim(1050, 100) skew.ax.set_xlim(-50, 60) #skew.ax.set_xticklabels('xtick', rotation=45, fontsize=14) skew.ax.tick_params(axis="x", labelsize=14, pad=10, rotation=45, labelcolor='orange') skew.ax.tick_params(axis="y", labelsize=14, pad=0.5) # Calculate full parcel profile and add to plot as black line #prof_0 = mpcalc.parcel_profile(p, T[0], Td[0]).to('degC') #skew.plot(p, prof_0, 'k', linewidth=1.5)
# # This code below is taken from Skew-T_Layout.py from the metpy examples # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Create a new figure. The dimensions here give a good aspect ratio fig = plt.figure(figsize=(11, 9)) add_metpy_logo(fig, 750, 80, size='large') # Grid for plots gs = gridspec.GridSpec(3, 3) skew = SkewT(fig, rotation=45, subplot=gs[:, :2]) # Plot the data using normal plotting functions, in this case using # log scaling in Y, as dictated by the typical meteorological plot skew.plot(pressure, temperature, 'r') skew.plot(pressure, dewpoint, 'g') skew.plot_barbs(pressure, u_wind, v_wind) skew.ax.set_ylim(1000, 100) # Add the relevant special lines skew.plot_dry_adiabats() skew.plot_moist_adiabats() skew.plot_mixing_lines() # Good bounds for aspect ratio skew.ax.set_xlim(-40, 60) # Create a hodograph ax = fig.add_subplot(gs[0, -1]) h = Hodograph(ax, component_range=60.)