def test_station_layout_names(): """Test getting station layout names.""" layout = StationPlotLayout() layout.add_barb('u', 'v') layout.add_text('E', 'stid') layout.add_value('W', 'temp') layout.add_symbol('C', 'cover', lambda x: x) assert sorted(layout.names()) == ['cover', 'stid', 'temp', 'u', 'v']
def test_station_layout_replace(): """Test that layout locations are replaced.""" layout = StationPlotLayout() layout.add_text("E", "temperature") layout.add_value("E", "dewpoint") assert "E" in layout assert layout["E"][0] is StationPlotLayout.PlotTypes.value assert layout["E"][1] == "dewpoint"
def test_station_layout_names(): """Test getting station layout names.""" layout = StationPlotLayout() layout.add_barb("u", "v") layout.add_text("E", "stid") layout.add_value("W", "temp") layout.add_symbol("C", "cover", lambda x: x) assert sorted(layout.names()) == ["cover", "stid", "temp", "u", "v"]
def test_station_layout_replace(): """Test that layout locations are replaced.""" layout = StationPlotLayout() layout.add_text('E', 'temperature') layout.add_value('E', 'dewpoint') assert 'E' in layout assert layout['E'][0] is StationPlotLayout.PlotTypes.value assert layout['E'][1] == 'dewpoint'
def test_layout_str(): """Test layout string representation.""" layout = StationPlotLayout() layout.add_barb('u', 'v') layout.add_text('E', 'stid') layout.add_value('W', 'temp') layout.add_symbol('C', 'cover', lambda x: x) assert str(layout) == ('{C: (symbol, cover, ...), E: (text, stid, ...), ' 'W: (value, temp, ...), barb: (barb, (\'u\', \'v\'), ...)}')
def test_layout_str(): """Test layout string representation.""" layout = StationPlotLayout() layout.add_barb("u", "v") layout.add_text("E", "stid") layout.add_value("W", "temp") layout.add_symbol("C", "cover", lambda x: x) assert str(layout) == ( "{C: (symbol, cover, ...), E: (text, stid, ...), " "W: (value, temp, ...), barb: (barb, ('u', 'v'), ...)}" )
def test_station_layout_odd_data(): """Test more corner cases with data passed in.""" fig = plt.figure(figsize=(9, 9)) # Set up test layout layout = StationPlotLayout() layout.add_barb('u', 'v') layout.add_value('W', 'temperature', units='degF') # Now only use data without wind and no units data = {'temperature': [25.]} # Make the plot sp = StationPlot(fig.add_subplot(1, 1, 1), [1], [2], fontsize=12) layout.plot(sp, data) assert True
def __init__(self, parent): StationPlotLayout.__init__(self) self.parent = parent self.add_barb('windU', 'windV', units='knots', linewidth=0.5) # tk.Toplevel( parent ); # tk.Frame.__init__(self, self.root); self.nCol = 5 self.nRow = 5 self.vars = {} self.traces = {} self.sCol = -(self.nCol // 2) self.sRow = -(self.nRow // 2) for i in range(self.sCol, self.sCol + self.nCol): for j in range(self.sRow, self.sRow + self.nRow): key = self.key(i, j) self.vars[key] = { 'name': tk.StringVar(), 'color': tk.StringVar() } if key in sfcLayout: self.vars[key]['name'].set(sfcLayout[key]['name']) self.vars[key]['color'].set(sfcLayout[key]['color']) self.update_value(key)
def test_station_layout_odd_data(): """Test more corner cases with data passed in.""" fig = plt.figure(figsize=(9, 9)) # Set up test layout layout = StationPlotLayout() layout.add_barb("u", "v") layout.add_value("W", "temperature", units="degF") # Now only use data without wind and no units data = dict(temperature=[25.0]) # Make the plot sp = StationPlot(fig.add_subplot(1, 1, 1), [1], [2], fontsize=12) layout.plot(sp, data) assert True
def __init__(self): tk.Tk.__init__(self) # Initialize the frame superclass self.initMenuBar() self.srfObs = awipsSurfaceObs() self.stnLayout = StationPlotLayout() self.plotFrame = matplotFrame(self) self.optFrame = optionsFrame(self) self.optFrame.cur_domain.trace('w', self.updateDomain) update = tk.Button(self, text='Update Stations') update.configure(command=self.updateObs) self.optFrame.setDefaults() update.grid(row=0, column=0, sticky='ew') self.optFrame.grid(row=1, column=0, sticky='nsew') self.plotFrame.grid(row=0, column=1, sticky='nsew', rowspan=2)
gl.ylabels_right = False # Make the station plot stationplot = StationPlot(display.ax, sfc_data['longitude'], sfc_data['latitude'], transform=cartopy.crs.PlateCarree(), fontsize=12) station_layout.plot(stationplot, sfc_data) return display, time_at_start_of_radar if __name__ == "__main__": disptype = sys.argv[1] if disptype == 'KLWX': plot_kwargs = dict(path_effects=[mpatheffects.withStroke(foreground='black', linewidth=1)], clip_on=True) layout = StationPlotLayout() layout.add_barb('eastward_wind', 'northward_wind', 'knots') layout.add_value('NW', 'air_temperature', color='red', **plot_kwargs) layout.add_value('SW', 'dew_point_temperature', color='green', **plot_kwargs) layout.add_value('NE', 'air_pressure_at_sea_level', units='mbar', fmt=lambda v: format(10 * v, '03.0f')[-3:], clip_on=True) layout.add_symbol('C', 'cloud_coverage', sky_cover, clip_on=True) layout.add_symbol('W', 'present_weather', current_weather, clip_on=True) bb = {'west':-79.5, 'east':-75.0,'north':40, 'south':37} display, tas = radar_plus_obs('KLWX', datetime.utcnow(), radar_title = 'KLWX ', station_radius=20000., station_layout=layout, field = 'reflectivity', vmin=-12, vmax=64, bb=bb) display.ax.add_feature(cartopy.feature.LAKES, zorder=0) fancy_date_string = tas.strftime('/home/ubuntu/KLWX_%Y%m%d_%H%M.png') lfds = tas.strftime('KLWX_%Y%m%d_%H%M.png') plt.savefig(fancy_date_string)
transform=ccrs.PlateCarree(), fontsize=12) # The layout knows where everything should go, and things are standardized using # the names of variables. So the layout pulls arrays out of `data` and plots them # using `stationplot`. simple_layout.plot(stationplot, data) plt.show() ########################################### # or instead, a custom layout can be used: # Just winds, temps, and dewpoint, with colors. Dewpoint and temp will be plotted # out to Farenheit tenths. Extra data will be ignored custom_layout = StationPlotLayout() custom_layout.add_barb('eastward_wind', 'northward_wind', units='knots') custom_layout.add_value('NW', 'air_temperature', fmt='.1f', units='degF', color='darkred') custom_layout.add_value('SW', 'dew_point_temperature', fmt='.1f', units='degF', color='darkgreen') # Also, we'll add a field that we don't have in our dataset. This will be ignored custom_layout.add_value('E', 'precipitation',
def test_stationlayout_api(): """Test the StationPlot API.""" fig = plt.figure(figsize=(9, 9)) # testing data x = np.array([1, 5]) y = np.array([2, 4]) data = {'temp': np.array([32., 212.]) * units.degF, 'u': np.array([2, 0]) * units.knots, 'v': np.array([0, 5]) * units.knots, 'stid': ['KDEN', 'KSHV'], 'cover': [3, 8]} # Set up the layout layout = StationPlotLayout() layout.add_barb('u', 'v', units='knots') layout.add_value('NW', 'temp', fmt='0.1f', units=units.degC, color='darkred') layout.add_symbol('C', 'cover', sky_cover, color='magenta') layout.add_text((0, 2), 'stid', color='darkgrey') layout.add_value('NE', 'dewpt', color='green') # This should be ignored # Make the plot sp = StationPlot(fig.add_subplot(1, 1, 1), x, y, fontsize=12) layout.plot(sp, data) sp.ax.set_xlim(0, 6) sp.ax.set_ylim(0, 6) return fig
def test_stationlayout_api(): """Test the StationPlot API.""" fig = plt.figure(figsize=(9, 9)) # testing data x = np.array([1, 5]) y = np.array([2, 4]) data = dict() data["temp"] = np.array([32.0, 212.0]) * units.degF data["u"] = np.array([2, 0]) * units.knots data["v"] = np.array([0, 5]) * units.knots data["stid"] = ["KDEN", "KSHV"] data["cover"] = [3, 8] # Set up the layout layout = StationPlotLayout() layout.add_barb("u", "v", units="knots") layout.add_value("NW", "temp", fmt="0.1f", units=units.degC, color="darkred") layout.add_symbol("C", "cover", sky_cover, color="magenta") layout.add_text((0, 2), "stid", color="darkgrey") layout.add_value("NE", "dewpt", color="green") # This should be ignored # Make the plot sp = StationPlot(fig.add_subplot(1, 1, 1), x, y, fontsize=12) layout.plot(sp, data) sp.ax.set_xlim(0, 6) sp.ax.set_ylim(0, 6) return fig
def uaPlot(data, level, date, save_dir, ds, td_option): custom_layout = StationPlotLayout() custom_layout.add_barb('eastward_wind', 'northward_wind', units='knots') custom_layout.add_value('NW', 'air_temperature', fmt='.0f', units='degC', color='darkred') # Geopotential height and smooth hght = ds.Geopotential_height_isobaric.metpy.sel( vertical=level * units.hPa, time=date, lat=slice(85, 15), lon=slice(360 - 200, 360 - 10)) smooth_hght = mpcalc.smooth_n_point(hght, 9, 10) # Temperature, smooth, and convert to Celsius tmpk = ds.Temperature_isobaric.metpy.sel(vertical=level * units.hPa, time=date, lat=slice(85, 15), lon=slice(360 - 200, 360 - 10)) smooth_tmpc = (mpcalc.smooth_n_point(tmpk, 9, 10)).to('degC') #Calculate Theta-e rh = ds.Relative_humidity_isobaric.metpy.sel(vertical=level * units.hPa, time=date, lat=slice(85, 15), lon=slice( 360 - 200, 360 - 10)) td = mpcalc.dewpoint_from_relative_humidity(tmpk, rh) te = mpcalc.equivalent_potential_temperature(level * units.hPa, tmpk, td) smooth_te = mpcalc.smooth_n_point(te, 9, 10) #decide on the height format based on the level if level == 250: custom_layout.add_value('NE', 'height', fmt=lambda v: format(v, '1')[1:4], units='m', color='black') cint = 120 tint = 5 if level == 300: custom_layout.add_value('NE', 'height', fmt=lambda v: format(v, '1')[1:4], units='m', color='black') cint = 120 tint = 5 if level == 500: custom_layout.add_value('NE', 'height', fmt=lambda v: format(v, '1')[0:3], units='m', color='black') cint = 60 tint = 5 if level == 700: custom_layout.add_value('NE', 'height', fmt=lambda v: format(v, '1')[1:4], units='m', color='black') custom_layout.add_value('SW', 'tdd', units='degC', color='green') custom_layout.add_value('SE', 'thetae', units='degK', color='orange') temps = 'Tdd, and Theta-e' cint = 30 tint = 4 if level == 850: custom_layout.add_value('NE', 'height', fmt=lambda v: format(v, '1')[1:4], units='m', color='black') if td_option == True: custom_layout.add_value('SW', 'dew_point_temperature', units='degC', color='green') temps = 'Td, and Theta-e' if td_option == False: custom_layout.add_value('SW', 'tdd', units='degC', color='green') temps = 'Tdd, and Theta-e' # custom_layout.add_value('SW', 'tdd', units='degC', color='green') # temps = 'Tdd, and Theta-e' custom_layout.add_value('SE', 'thetae', units='degK', color='orange') cint = 30 tint = 4 if level == 925: custom_layout.add_value('NE', 'height', fmt=lambda v: format(v, '1')[1:4], units='m', color='black') if td_option == True: custom_layout.add_value('SW', 'dew_point_temperature', units='degC', color='green') temps = 'Td, and Theta-e' if td_option == False: custom_layout.add_value('SW', 'tdd', units='degC', color='green') temps = 'Tdd, and Theta-e' custom_layout.add_value('SE', 'thetae', units='degK', color='orange') cint = 30 tint = 4 globe = ccrs.Globe(ellipse='sphere', semimajor_axis=6371200., semiminor_axis=6371200.) proj = ccrs.Stereographic(central_longitude=-105., central_latitude=90., globe=globe, true_scale_latitude=60) # Plot the image fig = plt.figure(figsize=(40, 40)) ax = fig.add_subplot(1, 1, 1, projection=proj) state_boundaries = feat.NaturalEarthFeature( category='cultural', name='admin_1_states_provinces_lines', scale='10m', facecolor='none') coastlines = feat.NaturalEarthFeature('physical', 'coastline', '50m', facecolor='none') lakes = feat.NaturalEarthFeature('physical', 'lakes', '50m', facecolor='none') countries = feat.NaturalEarthFeature('cultural', 'admin_0_countries', '50m', facecolor='none') ax.add_feature(state_boundaries, zorder=2, edgecolor='grey') ax.add_feature(lakes, zorder=2, edgecolor='grey') ax.add_feature(coastlines, zorder=2, edgecolor='grey') ax.add_feature(lakes, zorder=2, edgecolor='grey') ax.add_feature(countries, zorder=2, edgecolor='grey') ax.coastlines(resolution='50m', zorder=2, color='grey') ax.set_extent([-132., -70, 26., 80.], ccrs.PlateCarree()) stationData = dataDict(data) stationplot = StationPlot(ax, stationData['longitude'], stationData['latitude'], transform=ccrs.PlateCarree(), fontsize=22) custom_layout.plot(stationplot, stationData) # Plot Solid Contours of Geopotential Height cs = ax.contour(hght.lon, hght.lat, smooth_hght.m, range(0, 20000, cint), colors='black', transform=ccrs.PlateCarree()) clabels = plt.clabel(cs, fmt='%d', colors='white', inline_spacing=5, use_clabeltext=True, fontsize=22) # Contour labels with black boxes and white text for t in clabels: t.set_bbox({'facecolor': 'black', 'pad': 4}) t.set_fontweight('heavy') #Check levels for different contours if level == 250 or level == 300 or level == 500: # Plot Dashed Contours of Temperature cs2 = ax.contour(hght.lon, hght.lat, smooth_tmpc.m, range(-60, 51, tint), colors='red', transform=ccrs.PlateCarree()) clabels = plt.clabel(cs2, fmt='%d', colors='red', inline_spacing=5, use_clabeltext=True, fontsize=22) # Set longer dashes than default for c in cs2.collections: c.set_dashes([(0, (5.0, 3.0))]) temps = 'T' if level == 700 or level == 850 or level == 925: # Plot Dashed Contours of Temperature cs2 = ax.contour(hght.lon, hght.lat, smooth_te.m, range(210, 360, tint), colors='orange', transform=ccrs.PlateCarree()) clabels = plt.clabel(cs2, fmt='%d', colors='orange', inline_spacing=5, use_clabeltext=True, fontsize=22) # Set longer dashes than default for c in cs2.collections: c.set_dashes([(0, (5.0, 3.0))]) dpi = plt.rcParams['savefig.dpi'] = 255 date = date + timedelta(hours=6) text = AnchoredText(str(level) + 'mb Wind, Heights, and ' + temps + ' Valid: {0:%Y-%m-%d} {0:%H}:00UTC'.format(date), loc=3, frameon=True, prop=dict(fontsize=22)) ax.add_artist(text) plt.tight_layout() save_fname = '{0:%Y%m%d_%H}z_'.format(date) + str(level) + 'mb.pdf' plt.savefig(save_dir / save_fname, dpi=dpi, bbox_inches='tight')
stationplot = StationPlot(ax, data['longitude'], data['latitude'], transform=ccrs.PlateCarree(), fontsize=12) # The layout knows where everything should go, and things are standardized using # the names of variables. So the layout pulls arrays out of `data` and plots them # using `stationplot`. simple_layout.plot(stationplot, data) plt.show() ########################################### # or instead, a custom layout can be used: # Just winds, temps, and dewpoint, with colors. Dewpoint and temp will be plotted # out to Farenheit tenths. Extra data will be ignored custom_layout = StationPlotLayout() custom_layout.add_barb('eastward_wind', 'northward_wind', units='knots') custom_layout.add_value('NW', 'air_temperature', fmt='.1f', units='degF', color='darkred') custom_layout.add_value('SW', 'dew_point_temperature', fmt='.1f', units='degF', color='darkgreen') # Also, we'll add a field that we don't have in our dataset. This will be ignored custom_layout.add_value('E', 'precipitation', fmt='0.2f', units='inch', color='blue') # Create the figure and an axes set to the projection fig = plt.figure(figsize=(20, 10)) ax = fig.add_subplot(1, 1, 1, projection=proj) # Add some various map elements to the plot to make it recognizable ax.add_feature(feat.LAND, zorder=-1) ax.add_feature(feat.OCEAN, zorder=-1)