def empty_skewt(self): #First create the figure and SkewT objects fig = pp.figure(figsize=(9, 9)) skewt = SkewT(fig, rotation=45) #Now set the limits skewt.ax.set_xlim(-40, 60) skewt.ax.set_ylim(1000, 100) #Add the adiabats, etc skewt.plot_dry_adiabats(t0=numpy.arange(-40, 200, 10) * self.sounding_units["temp"]) skewt.plot_moist_adiabats() try: skewt.plot_mixing_lines(pressure=self.sounding["pres"]) except: skewt.plot_mixing_lines(p=self.sounding["pres"]) #Adjust the axis labels skewt.ax.set_xlabel("Temperature ('C)", fontsize=14, fontweight="bold") skewt.ax.set_ylabel("Pressure (hPa)", fontsize=14, fontweight="bold") #Returning return fig, skewt
def plot_metpy(data, title="", saveplot=None, showplot=True): # Convert data into a suitable format for metpy. _altitude = data[:,0] * units('m') p = mpcalc.height_to_pressure_std(_altitude) T = data[:,3] * units.degC Td = data[:,4] * units.degC wind_speed = data[:,1] * units('m/s') wind_direction = data[:,2] * units.degrees u, v = mpcalc.wind_components(wind_speed, wind_direction) fig = plt.figure(figsize=(6,8)) skew = SkewT(fig=fig) skew.plot(p, T, 'r') skew.plot(p, Td, 'g') my_interval = np.arange(300, 1000, 50) * units('mbar') ix = mpcalc.resample_nn_1d(p, my_interval) skew.plot_barbs(p[ix], u[ix], v[ix]) skew.ax.set_ylim(1000,300) skew.ax.set_xlim(-40, 30) skew.plot_dry_adiabats() heights = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]) * units.km std_pressures = mpcalc.height_to_pressure_std(heights) for height_tick, p_tick in zip(heights, std_pressures): trans, _, _ = skew.ax.get_yaxis_text1_transform(0) skew.ax.text(0.02, p_tick, '---{:~d}'.format(height_tick), transform=trans) plt.title("Sounding: " + title) if saveplot != None: fig.savefig(saveplot, bbox_inches='tight')
def test_skewt_barb_unit_conversion_exception(u, v): """Test that errors are raise if unit conversion is requested on un-united data.""" p_wind = np.array([500]) * units.hPa fig = plt.figure(figsize=(9, 9)) skew = SkewT(fig) with pytest.raises(ValueError): skew.plot_barbs(p_wind, u, v, plot_units='knots')
def test_skewt_barb_unit_conversion_exception(u, v): """Test that errors are raise if unit conversion is requested on un-united data.""" p_wind = np.array([500]) * units.hPa fig = plt.figure(figsize=(9, 9)) skew = SkewT(fig, aspect='auto') with pytest.raises(ValueError): skew.plot_barbs(p_wind, u, v, plot_units='knots')
def test_skewt_barb_color(): """Test plotting colored wind barbs on the Skew-T.""" fig = plt.figure(figsize=(9, 9)) skew = SkewT(fig) p = np.linspace(1000, 100, 10) u = np.linspace(-10, 10, 10) skew.plot_barbs(p, u, u, c=u) 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) return fig
def test_skewt_barb_no_default_unit_conversion(): """Test that barbs units are left alone by default (#737).""" u_wind = np.array([3.63767155210412]) * units('m/s') v_wind = np.array([3.63767155210412]) * units('m/s') p_wind = np.array([500]) * units.hPa fig = plt.figure(figsize=(9, 9)) skew = SkewT(fig) skew.plot_barbs(p_wind, u_wind, v_wind) return fig
def test_skewt_barb_unit_conversion(): """Test that barbs units can be converted at plot time (#737).""" u_wind = np.array([3.63767155210412]) * units('m/s') v_wind = np.array([3.63767155210412]) * units('m/s') p_wind = np.array([500]) * units.hPa fig = plt.figure(figsize=(9, 9)) skew = SkewT(fig) skew.plot_barbs(p_wind, u_wind, v_wind, plot_units='knots') return fig
def test_skewt_barb_no_default_unit_conversion(): """Test that barbs units are left alone by default (#737).""" u_wind = np.array([3.63767155210412]) * units('m/s') v_wind = np.array([3.63767155210412]) * units('m/s') p_wind = np.array([500]) * units.hPa fig = plt.figure(figsize=(9, 9)) skew = SkewT(fig) skew.ax.set_ylabel('') # remove_text doesn't do this as of pytest 0.9 skew.plot_barbs(p_wind, u_wind, v_wind) skew.ax.set_ylim(1000, 500) skew.ax.set_yticks([1000, 750, 500]) 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_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_barb_unit_conversion(): """Test that barbs units can be converted at plot time (#737).""" u_wind = np.array([3.63767155210412]) * units('m/s') v_wind = np.array([3.63767155210412]) * units('m/s') p_wind = np.array([500]) * units.hPa fig = plt.figure(figsize=(9, 9)) skew = SkewT(fig, aspect='auto') skew.ax.set_ylabel('') # remove_text doesn't do this as of pytest 0.9 skew.plot_barbs(p_wind, u_wind, v_wind, plot_units='knots') skew.ax.set_ylim(1000, 500) skew.ax.set_yticks([1000, 750, 500]) skew.ax.set_xlim(-20, 20) return fig
def plot(self, picPath=Path('.'), showmode=False, savemode=True): ## fig setting grid = gs.GridSpec(3, 3) fig = plt.figure(figsize=(12, 12)) # fig.subplots_adjust(top = 0.9, bottom = 0.1, left = 0.05, right = 0.96, wspace = 0.08, hspace = 0.25) # skew = SkewT(fig, subplot=grid[:, :2], rotation=45) skew = SkewT(fig, rotation=45) self.plotter(skew) ## UTC UTC = max((self.release_time + dtmdt(minutes=25)).hour, (self.release_time - dtmdt(minutes=25)).hour) - 8 if (UTC < 0): UTC += 24 title = (self.release_time - dtmdt(days=1)).strftime('%Y%m%d') else: title = self.release_time.strftime('%Y%m%d') fig.text(0.55, 0.89, f"no_{self.no} {self.release_time} LST", fontsize=self.fs - 6) skew.ax.set_title( f"Skew-T Log-P Diagram Storm tracker {title} {UTC:02d} UTC\n") if (savemode == True): plt.savefig(picPath / ( f"{title}_{UTC:02d}Z_{self.release_time.strftime('%Y%m%d_%H%M')}_no{self.no}.png" )) if (showmode == True): plt.show()
def plot(self, picPath=Path('.'), showmode=False): ## fig setting grid = gs.GridSpec(3, 3) fig = plt.figure(figsize=(12, 12)) # fig.subplots_adjust(top = 0.9, bottom = 0.1, left = 0.05, right = 0.96, wspace = 0.08, hspace = 0.25) # skew = SkewT(fig, subplot=grid[:, :], rotation=45) skew = SkewT(fig, rotation=45) self.plotter(skew) ## UTC UTC = self.release_time.hour fig.text(0.55, 0.89, f"{self.release_time+dtmdt(hours=8)} LST", fontsize=self.fs - 6) skew.ax.set_title(f"Skew-T Log-P Diagram RS41 {UTC:02d} UTC\n", fontsize=self.fs) plt.savefig(picPath / ( f"{self.release_time.strftime('%Y%m%d')}_{UTC:02d}Z_{(self.release_time+dtmdt(hours=8)).strftime('%Y%m%d_%H%M')}.png" )) if (showmode == True): plt.show()
def test_skewt_shade_area_kwargs(test_profile): """Test shading areas on a SkewT plot with kwargs.""" 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, facecolor='m') return fig
def test_skewt_default_aspect_empty(): """Test SkewT with default aspect and no plots, only special lines.""" # With this rotation and the default aspect, this matches exactly the NWS SkewT PDF fig = plt.figure(figsize=(12, 9)) skew = SkewT(fig, rotation=43) skew.plot_dry_adiabats() skew.plot_moist_adiabats() skew.plot_mixing_lines() return fig
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 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) return fig
def test_skewt_shade_cape_cin_no_limit(test_profile): """Test shading CIN without limits.""" p, t, _, tp = test_profile with matplotlib.rc_context({'axes.autolimit_mode': 'data'}): fig = plt.figure(figsize=(9, 9)) skew = SkewT(fig, aspect='auto') 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) skew.ax.set_ylim(1000, 100) # This works around the fact that newer pint versions default to degrees_Celsius skew.ax.set_xlabel('degC') 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_adiabat_units(): """Test adiabats and mixing lines can handle different units.""" with matplotlib.rc_context({'axes.autolimit_mode': 'data'}): fig = plt.figure(figsize=(9, 9)) skew = SkewT(fig) p = np.linspace(950, 100, 10) * units.hPa t = np.linspace(18, -20, 10) * units.degC skew.plot(p, t, 'r') # Add lines with units different to the xaxis t0 = (np.linspace(-20, 20, 5) * units.degC).to(units.degK) skew.plot_dry_adiabats(t0=t0) # add lines with no units t0 = np.linspace(-20, 20, 5) skew.plot_moist_adiabats(t0=t0) skew.plot_mixing_lines() return fig
def test_skewt_units(): """Test that plotting with SkewT works with units properly.""" fig = plt.figure(figsize=(9, 9)) skew = SkewT(fig, aspect='auto') skew.ax.axvline(np.array([273]) * units.kelvin, color='purple') skew.ax.axhline(np.array([50000]) * units.Pa, color='red') skew.ax.axvline(np.array([-20]) * units.degC, color='darkred') skew.ax.axvline(-10, color='orange') return fig
def test_skewt_adiabat_kelvin_base(): """Test adiabats and mixing lines can handle different units.""" with matplotlib.rc_context({'axes.autolimit_mode': 'data'}): fig = plt.figure(figsize=(9, 9)) skew = SkewT(fig, rotation=45) p = np.linspace(950, 100, 10) * units.hPa t = (np.linspace(18, -30, 10) * units.degC).to(units.degK) skew.plot(p, t, 'r') # At this point the xaxis is actually degC # Add lines using kelvin base t0 = (np.linspace(-20, 40, 5) * units.degC).to(units.degK) skew.plot_dry_adiabats(t0=t0) # add lines with no units (but using kelvin) t0 = np.linspace(253.15, 313.15, 5) skew.plot_moist_adiabats(t0=t0) skew.plot_mixing_lines() return fig
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_area(test_profile): """Test shading areas 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, aspect='auto') skew.plot(p, t, 'r') skew.plot(p, tp, 'k') skew.shade_area(p, t, tp) skew.ax.set_xlim(-50, 50) skew.ax.set_ylim(1000, 100) return fig
def add_subplots(self, subplot_shape=(1,), **kwargs): """ Adds subplots to the Display object. The current figure in the object will be deleted and overwritten. Parameters ---------- subplot_shape : 1 or 2D tuple, list, or array The structure of the subplots in (rows, cols). subplot_kw : dict, optional The kwargs to pass into fig.subplots. **kwargs : keyword arguments Any other keyword arguments that will be passed into :func:`matplotlib.pyplot.figure` when the figure is made. The figure is only made if the *fig* property is None. See the matplotlib documentation for further details on what keyword arguments are available. """ del self.axes if self.fig is None: self.fig = plt.figure(**kwargs) self.SkewT = np.empty(shape=subplot_shape, dtype=SkewT) self.axes = np.empty(shape=subplot_shape, dtype=plt.Axes) if len(subplot_shape) == 1: for i in range(subplot_shape[0]): subplot_tuple = (subplot_shape[0], 1, i + 1) self.SkewT[i] = SkewT(fig=self.fig, subplot=subplot_tuple) self.axes[i] = self.SkewT[i].ax elif len(subplot_shape) == 2: for i in range(subplot_shape[0]): for j in range(subplot_shape[1]): subplot_tuple = (subplot_shape[0], subplot_shape[1], i * subplot_shape[1] + j + 1) self.SkewT[i] = SkewT(fig=self.fig, subplot=subplot_tuple) self.axes[i] = self.SkewT[i].ax else: raise ValueError("Subplot shape must be 1 or 2D!")
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 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, aspect='auto') skew.plot(p, t, 'r') skew.plot(p, tp, 'k') skew.shade_area(p, t, tp, facecolor='m') skew.ax.set_xlim(-50, 50) skew.ax.set_ylim(1000, 100) # This works around the fact that newer pint versions default to degrees_Celsius skew.ax.set_xlabel('degC') return fig
def test_skewt_wide_aspect_ratio(test_profile): """Test plotting a skewT with a wide aspect ratio.""" p, t, tp = test_profile fig = plt.figure(figsize=(12.5, 3)) skew = SkewT(fig, aspect='auto') skew.plot(p, t, 'r') skew.plot(p, tp, 'k') skew.ax.set_xlim(-30, 50) skew.ax.set_ylim(1050, 700) return fig
def test_skewt_wide_aspect_ratio(test_profile): """Test plotting a skewT with a wide aspect ratio.""" p, t, _, tp = test_profile fig = plt.figure(figsize=(12.5, 3)) skew = SkewT(fig, aspect='auto') skew.plot(p, t, 'r') skew.plot(p, tp, 'k') skew.ax.set_xlim(-30, 50) skew.ax.set_ylim(1050, 700) # This works around the fact that newer pint versions default to degrees_Celsius skew.ax.set_xlabel('degC') return fig
def compare_interpolated_to_real(Tint, date='2014-03-02T12:00', sound_path=sound_path): from metpy.plots import SkewT from metpy.units import units import pandas as pd import xarray as xr import matplotlib.pyplot as plt 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) T = da.sel(time=dt, var='TEMP').values * units.degC Tm = Tint.sel(time=dt).values * units.degC pm = Tint['pressure'].values * units.hPa fig = plt.figure(figsize=(9, 9)) title = da.attrs['description'] + ' ' + dt.strftime('%Y-%m-%d') skew = SkewT(fig) skew.plot(p, T, 'r', linewidth=2) skew.plot(pm, Tm, 'g', linewidth=2) skew.ax.set_title(title) skew.ax.legend(['Original', 'Interpolated']) return
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(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()
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 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
# coding: utf-8 import matplotlib.pyplot as plt import numpy as np from scipy.constants import C2K, K2C 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
# Why do I get 0-1.0 ticks and labels? Erase them. ax.get_xaxis().set_visible(False) # put after plt.tight_layout or axis labels will be cut off ax.get_yaxis().set_visible(False) for sfile in sfiles: title, station, init_time, valid_time, fhr = get_title(sfile) # Avoid './' on the beginning for rsync command to not produce "skipping directory ." message. ofile = project+'.skewt.'+station+'.hr'+'%03d'%fhr+'.png' if debug: print 'ofile=',ofile if not force_new and os.path.isfile(ofile): print 'ofile exists and force_new=', force_new, 'skipping.' continue skew = SkewT(fig, rotation=30) skew.ax.set_ylabel('Pressure (hPa)') skew.ax.set_xlabel('Temperature (C)') # example of a slanted line at constant temperature l = skew.ax.axvline(-20, color='b', linestyle='dashed', alpha=0.5, linewidth=1) l = skew.ax.axvline(0, color='b', linestyle='dashed', alpha=0.5, linewidth=1) if fhr % args.interval != 0: print "fhr not multiple of", args.interval, "skipping", sfile continue if len(station) > 3 and station not in no_ignore_station: print "skipping", sfile continue skew.ax.set_title(title, horizontalalignment="left", x=0, fontsize=12) print "reading", sfile data = open(sfile).read() pres, hght, tmpc, dwpc, wdir, wspd, latitude, longitude = parseGEMPAK(data)
# # 1. Create a ``Figure`` object and set the size of the figure. # # 2. Create a ``SkewT`` object # # 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
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 test_skewt_gridspec(): """Test using SkewT on a sub-plot.""" fig = plt.figure(figsize=(9, 9)) gs = GridSpec(1, 2) SkewT(fig, subplot=gs[0, 1]) return fig
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()
# Change default to be better for skew-T plt.rcParams['figure.figsize'] = (9, 9) 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) ###########################################
def test_skewt_with_grid_enabled(): """Test using SkewT when gridlines are already enabled (#271).""" with plt.rc_context(rc={'axes.grid': True}): # Also tests when we don't pass in Figure SkewT()
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='blue') # 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