MetPy Intro: NYS Mesonet Map


Overview

In this notebook, we’ll use Cartopy, Matplotlib, and Pandas (with a bunch of help from MetPy) to read in, manipulate, and visualize current data from the New York State Mesonet.

Prerequisites

Concepts

Importance

Notes

Matplotlib

Necessary

Cartopy

Necessary

Pandas

Necessary

MetPy

Necessary

Intro

  • Time to learn: 30 minutes


Imports

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from datetime import datetime
from cartopy import crs as ccrs
from cartopy import feature as cfeature
from metpy.calc import wind_components, dewpoint_from_relative_humidity
from metpy.units import units
from metpy.plots import StationPlot
ERROR 1: PROJ: proj_create_from_database: Open of /knight/anaconda_aug22/envs/aug22_env/share/proj failed

Create a Pandas DataFrame object pointing to the most recent set of NYSM obs.

nysm_data = pd.read_csv('https://www.atmos.albany.edu/products/nysm/nysm_latest.csv')
nysm_data.columns
Index(['station', 'time', 'temp_2m [degC]', 'temp_9m [degC]',
       'relative_humidity [percent]', 'precip_incremental [mm]',
       'precip_local [mm]', 'precip_max_intensity [mm/min]',
       'avg_wind_speed_prop [m/s]', 'max_wind_speed_prop [m/s]',
       'wind_speed_stddev_prop [m/s]', 'wind_direction_prop [degrees]',
       'wind_direction_stddev_prop [degrees]', 'avg_wind_speed_sonic [m/s]',
       'max_wind_speed_sonic [m/s]', 'wind_speed_stddev_sonic [m/s]',
       'wind_direction_sonic [degrees]',
       'wind_direction_stddev_sonic [degrees]', 'solar_insolation [W/m^2]',
       'station_pressure [mbar]', 'snow_depth [cm]', 'frozen_soil_05cm [bit]',
       'frozen_soil_25cm [bit]', 'frozen_soil_50cm [bit]',
       'soil_temp_05cm [degC]', 'soil_temp_25cm [degC]',
       'soil_temp_50cm [degC]', 'soil_moisture_05cm [m^3/m^3]',
       'soil_moisture_25cm [m^3/m^3]', 'soil_moisture_50cm [m^3/m^3]', 'lat',
       'lon', 'elevation', 'name'],
      dtype='object')

Create several Series objects for some of the columns.

stid = nysm_data['station']
lats = nysm_data['lat']
lons = nysm_data['lon']

Our goal is to make a map of NYSM observations, which includes the wind velocity. The convention is to plot wind velocity using wind barbs. The MetPy library allows us to not only make such a map, but perform a variety of meteorologically-relevant calculations and diagnostics. Here, we will use such a calculation, which will determine the two scalar components of wind velocity (u and v), from wind speed and direction. We will use MetPy’s wind_components method.

This method requires us to do the following:

  1. Create Pandas Series objects for the variables of interest

  2. Extract the underlying Numpy array via the Seriesvalues attribute

  3. Attach units to these arrays using MetPy’s units class

Perform these three steps

wspd = nysm_data['max_wind_speed_prop [m/s]'].values * units['m/s']
drct = nysm_data['wind_direction_prop [degrees]'].values * units['degree']
Tip: The * operator might make you think that we're multiplying. However, in this case we use it to "attach" units to an array of values.

Examine these two units aware Series

wspd
Magnitude
[5.4 4.6 3.5 8.1 6.3 2.1 5.2 6.2 4.3 7.8 5.3 8.8 3.3 9.6 3.8 0.8 3.6 4.7
1.9 4.9 3.7 4.8 3.6 3.3 4.0 4.1 4.7 3.3 4.7 6.8 6.7 4.3 2.1 3.9 4.7 5.3
6.3 6.3 5.5 2.7 2.5 5.6 5.8 6.1 5.9 4.5 5.1 4.0 4.8 5.4 4.4 3.2 4.6 4.3
3.5 5.1 8.9 6.7 3.5 7.9 4.1 6.3 3.6 2.7 5.1 7.5 2.5 4.2 6.5 7.2 3.1 4.3
4.5 4.6 3.4 7.0 3.9 3.0 5.0 4.5 5.2 2.3 5.5 1.9 9.7 4.6 3.0 4.6 6.5 5.1
4.2 2.6 4.9 3.0 4.5 4.2 5.2 5.9 8.3 4.1 6.2 5.4 8.6 7.3 5.2 6.6 5.1 8.2
3.3 2.6 4.1 3.5 7.0 6.1 8.3 3.8 7.3 5.2 5.4 4.1 7.5 2.6 5.2 6.5 3.1 2.6]
Unitsmeter/second
Tip: This is a unique type of object: not only does it have values, aka magnitude, but it also has Units attached. This is a very nice property, since it will make calculations that require awareness of units much easier!
drct
Magnitude
[359 340 304 347 320 303 358 309 326   7 307 352 353  11 308  81 297 330
318 305 186 316 30 345 351 338 309 289 325 320 18 304 4 316 347 326
341 285 340 67 24 290 252 10 10 323 329 302 68 317 348 12 324 298
10 15 277 15 329 246 340 324 314 300 292 25 326 288 298 333 259 52
354 295 301 260 284 294 313 340 8 9 336 267 15 326 299 343 18 303
312 289 318 16 332 4 326 312 351 340 274 293 353 6 329 16 327 9
328 280 31 310 36 357 337 347 319 16 319 225 288 58 20 28 275 309]
Unitsdegree

Convert wind speed from m/s to knots

wspk = wspd.to('knots')

Perform the vector decomposition

u, v = wind_components(wspk, drct)

Take a look at one of the output components:

u
Magnitude
[0.1831937263179225 3.058236270773797 5.640320418031061 3.541885931245742
7.871718675858918 3.4235148453927695 0.3527638111613474 9.366035561403667
4.674031396180969 -1.8477814054084998 8.227843159666497
2.3806716190145183 0.781753671518979 -3.5606689417998862
5.820727380853108 -1.535930032890927 6.235121249179939 4.568034557235424
2.4713031033988067 7.802290529836834 0.7517921872166008 6.481477668213541
-3.498920086393088 1.6602431186921955 1.2163370931853825
2.9855255501181786 7.10005921590278 6.065205549740759 5.240233964935046
8.496458253308038 -4.02456258332815 6.929536513581017 -0.2847510483291508
5.266200605423502 2.05516837985864 5.76101544180445 3.986979342920256
11.828940464490321 3.6565868454904096 -4.831159382050605
-1.9765819587916862 10.229051422809887 10.72249463296048
-2.059024828059282 -1.9915158173032403 5.264256681999558
5.105885019086716 6.593894484153637 -8.6510459000616 7.158773282729464
1.7782511784845125 -1.2932735843523695 5.255790376870063
7.380145106617813 -1.1814076882307358 -2.565830274342485 17.1712627962138
-3.3707966349205196 3.5040387385889233 14.028743420818342
2.7258192848201235 7.198147690061174 5.033824952693801 4.545230520942086
9.19173626881545 -6.161281353671105 2.7174601140587034 7.764565079040349
11.156033300701345 6.3539059142813485 5.915204841941648
-6.586612562544308 0.914341849317487 8.103918441321232 5.665079784337935
13.400191887639117 7.355805613884986 5.327370919298105 7.10818932459237
2.9917528735830627 -1.4067605021449385 -0.6993938285815938
4.348480309341708 3.688242990130284 -4.880108561004334 5.000126609868014
5.100374102108786 2.6142955886655117 -3.9044263868108913 8.31425033881101
6.067143499577866 4.778646796765448 6.373360635081133 -1.6073884680472956
4.106608702554769 -0.5695020966583016 5.652317037242104 8.522892058930813
2.523899468359669 2.7258192848201235 12.022478186716674 9.662318764101212
2.0372974469888545 -1.4832656666705906 5.206000411617829
-3.5362546297040502 5.399337301768842 -2.4934910410300297
3.3992661226190473 4.97721412969453 -4.104731093775594 5.2117494510254465
-7.997941877845746 0.6205710578267054 6.3040205827535125
1.6616254986091137 9.30952013059964 -2.7861400112819794 6.886494343183296
5.635473050925184 13.865294784000623 -4.286031414699864
-3.457136653918208 -5.931768125912442 6.002987489580929
3.9276923322015382]
Unitsknot
Exercise: Create a 2-meter temperature object; attach units of degrees Celsius (degC) to it, and then convert to Fahrenheit (degF).
# Write your code here
# %load /spare11/atm350/common/mar09/mar09.py
tmpc = nysm_data['temp_2m [degC]'].values * units('degC')
tmpf = tmpc.to('degF')

Now, let’s plot several of the meteorological values on a map. We will use Matplotlib and Cartopy, as well as MetPy’s StationPlot method.

Create units-aware objects for relative humidity and station pressure

rh = nysm_data['relative_humidity [percent]'].values * units('percent')
pres = nysm_data['station_pressure [mbar]'].values * units('mbar')

Plot the map, centered over NYS, with add some geographic features, and the mesonet data.

Determine the current time, for use in the plot’s title and a version to be saved to disk.

timeString = nysm_data['time'][0]
timeObj = datetime.strptime(timeString,"%Y-%m-%d %H:%M:%S")
titleString = datetime.strftime(timeObj,"%B %d %Y, %H%M UTC")
figString = datetime.strftime(timeObj,"%Y%m%d_%H%M")

Previously, we used the ax.scatter and ax.text methods to plot markers for the stations and their site id’s. The latter method does not provide an intuitive means to orient several text stings relative to a central point as we typically do for a meteorological surface station plot. Let’s take advantage of the Metpy package, and its StationPlot method!

Be patient: this may take a minute or so to plot, if you chose the highest resolution for the shapefiles!

# Set the domain for defining the plot region.
latN = 45.2
latS = 40.2
lonW = -80.0
lonE = -72.0
cLat = (latN + latS)/2
cLon = (lonW + lonE )/2

res = '50m'
proj = ccrs.LambertConformal(central_longitude=cLon, central_latitude=cLat)

fig = plt.figure(figsize=(18,12),dpi=150) # Increase the dots per inch from default 100 to make plot easier to read
ax = fig.add_subplot(1,1,1,projection=proj)
ax.set_extent ([lonW,lonE,latS,latN])
ax.set_facecolor(cfeature.COLORS['water'])
ax.add_feature (cfeature.STATES.with_scale(res))
ax.add_feature (cfeature.RIVERS.with_scale(res))
ax.add_feature (cfeature.LAND.with_scale(res))
ax.add_feature (cfeature.COASTLINE.with_scale(res))
ax.add_feature (cfeature.LAKES.with_scale(res))
ax.add_feature (cfeature.STATES.with_scale(res))

# Create a station plot pointing to an Axes to draw on as well as the location of points
stationplot = StationPlot(ax, lons, lats, transform=ccrs.PlateCarree(),
                          fontsize=8)

stationplot.plot_parameter('NW', tmpf, color='red')
stationplot.plot_parameter('SW', rh, color='green')
stationplot.plot_parameter('NE', pres, color='purple')
stationplot.plot_barb(u, v,zorder=2) # zorder value set so wind barbs will display over lake features

plotTitle = f'NYSM Temperature($^\circ$F), RH (%), Station Pressure (hPa), Peak 5-min Wind (kts), {titleString}'
ax.set_title (plotTitle);
../../_images/01_Metpy_NYSMMap_34_0.png
Tip: In the code cell above, the plotTitle string object, uses f-strings, which is a newer and better way of constructing more complex string objects in Python.

What if we wanted to plot sea-level pressure (SLP) instead of station pressure? In this case, we can apply what’s called a reduction to sea-level pressure formula. This formula requires station elevation (accounting for sensor height) in meters, temperature in Kelvin, and station pressure in hectopascals. We assume each NYSM station has its sensor height .5 meters above ground level.

Tip: At present, MetPy does not yet have a function that reduces station pressure to SLP, so we will do a units-unaware calculation. We can strip the units ... i.e., take only the magnitude of the units-aware variables via their .m attribute.
pres.m
array([ 962.53,  959.89,  992.48, 1009.73,  966.7 , 1007.9 ,  973.94,
        976.76,  959.14, 1015.56,  999.75,  997.55, 1005.45, 1012.82,
        962.38, 1007.74, 1004.69,  955.63, 1015.54, 1006.72, 1015.66,
       1017.89,  981.59,  972.85,  951.1 , 1002.14,  970.62,  982.83,
        952.41,  970.63,  995.47,  994.78,  973.36, 1009.03,  949.92,
        985.72, 1004.91,  971.41,  979.78,  982.05,  999.7 ,  979.73,
        987.82,  984.07, 1018.01, 1003.89,  997.31,  958.91, 1010.65,
        993.69,  977.2 ,  951.31, 1011.63,  959.67,  964.49,  936.83,
        997.22,  997.35,  962.74,  994.36, 1011.33, 1012.79,  963.41,
       1015.23,  996.14, 1007.99, 1006.96,  975.54,  977.57,  967.1 ,
        962.61,  986.28,  959.13,  968.83, 1014.09,  978.77,  983.48,
       1014.88,  992.15,  969.86,  994.52, 1009.44,  957.23, 1009.78,
       1012.85,  970.42,  958.26,  978.04, 1013.35,  952.77, 1003.72,
        985.49,  982.42, 1010.22, 1008.89, 1018.91,  977.07,  981.  ,
        997.61, 1017.37,  998.84,  968.27, 1015.5 ,  985.97, 1013.88,
        998.36,  935.79, 1013.85,  978.87,  962.88,  980.05, 1008.13,
       1007.72,  955.38, 1018.28,  959.81, 1000.32, 1008.13,  968.72,
       1014.9 , 1000.42,  948.86,  970.29, 1019.04, 1011.59, 1004.2 ])
elev = nysm_data['elevation']
sensorHeight = .5
# Reduce station pressure to SLP. Source: https://www.sandhurstweather.org.uk/barometric.pdf 
slp = pres.m/np.exp(-1*(elev+sensorHeight)/((tmpc.m + 273.15) * 29.263))
slp
0      1025.205766
1      1024.353426
2      1027.414943
3      1020.962335
4      1025.713979
          ...     
121    1025.108480
122    1026.126808
123    1023.728015
124    1027.146649
125    1026.637546
Name: elevation, Length: 126, dtype: float64

Make a new map, substituting SLP for station pressure. We will also use the convention of the three least-significant digits to represent SLP in hectopascals.

Examples: 1018.4 hPa would be plotted as 184, while 977.2 hPa would be plotted as 772.
fig = plt.figure(figsize=(18,12),dpi=150) # Increase the dots per inch from default 100 to make plot easier to read
ax = fig.add_subplot(1,1,1,projection=proj)
ax.set_extent ([lonW,lonE,latS,latN])
ax.set_facecolor(cfeature.COLORS['water'])
ax.add_feature (cfeature.STATES.with_scale(res))
ax.add_feature (cfeature.RIVERS.with_scale(res))
ax.add_feature (cfeature.LAND.with_scale(res))
ax.add_feature (cfeature.COASTLINE.with_scale(res))
ax.add_feature (cfeature.LAKES.with_scale(res))
ax.add_feature (cfeature.STATES.with_scale(res))

stationplot = StationPlot(ax, lons, lats, transform=ccrs.PlateCarree(),
                          fontsize=8)

stationplot.plot_parameter('NW', tmpf, color='red')
stationplot.plot_parameter('SW', rh, color='green')
# A more complex example uses a custom formatter to control how the sea-level pressure
# values are plotted. This uses the standard trailing 3-digits of the pressure value
# in tenths of millibars.
stationplot.plot_parameter('NE', slp, color='purple', formatter=lambda v: format(10 * v, '.0f')[-3:])
stationplot.plot_barb(u, v,zorder=2)
plotTitle = f'NYSM Temperature($^\circ$F), RH (%), SLP(hPa), Peak 5-min Wind (kts), {titleString}'
ax.set_title (plotTitle);
../../_images/01_Metpy_NYSMMap_43_0.png

One last thing to do … plot dewpoint instead of RH. MetPy’s dewpoint_from_relative_humidity takes care of this!

dwpc = dewpoint_from_relative_humidity(tmpf, rh)
dwpc
Magnitude
[-3.8973443699255768 -5.315778121487085 -5.300826337218609
-4.21949912317848 -4.597133272433098 -6.005870885092861
-3.216440854131349 -4.271318791415524 -4.303672069089373
-3.3414761853676964 -3.7873290290016826 -4.388742848808818
-6.183540935811493 -3.373687356688947 -5.429046235130386
-4.644532013625053 -5.13563010454169 -4.480952162650965
-6.371930309756976 -5.923901922749053 -5.114698010986956
-6.1396558421129726 -5.149892501615568 -5.025791581911449
-5.968775374851987 -4.113880327454467 -3.7911582881989148
-6.311816727970154 -4.286251809422367 -6.167201372744103
-4.780509400693859 -6.857574722533627 -7.13441581462331 -5.71791249884518
-4.088387283620534 -3.7053128523206738 -4.727552443869115
-5.407183567317418 -3.5960278855559977 -5.20753107965686
-7.492640362347004 -4.337617424679763 -7.541143127070995
-4.680171360506449 -6.151469693458694 -5.171840440573874
-3.9365573113182677 -7.602022035076345 -4.349405930144314
-6.878380516499476 -4.627580815501005 -4.437456378066656
-7.243125681317963 -6.140896708879325 -7.270051276612378
-4.904485150658218 -5.157232098276381 -4.968127573469644
-5.987415928476423 -4.328881685774377 -4.713764325836792
-3.7138614439010667 -4.906299694342806 -8.203623313829553
-7.792224265236484 -3.0691543138815973 -5.813642731982327
-5.252870949141823 -5.364995935896161 -4.39750198018271
-6.166144042776693 -5.019773609522815 -6.743532497010335
-3.7947343538076552 -5.1645594496302465 -5.205212228619075
-6.045372787480403 -5.2445693764965995 -4.371819123611601
-4.280920076527195 -3.7420017261421776 -6.706223398624047
-5.733775434480492 -7.876208241497011 -2.879068556855316
-3.9499926541154764 -6.524408718152188 -6.628389789300115
-4.764756502983516 -5.697775207905977 -4.316630838149592
-6.529286034615836 -4.3022306727547175 -4.1924710359682535
-4.79070516365897 -4.6454055154343905 -4.7485248797314625
-4.9949776425529535 -4.185489111537379 -2.191527250725528
-5.0563359639073155 -5.989720084519263 -3.2772130508799364
-4.597332753809212 -1.735365186463639 -3.51923881814713
-6.881422845895713 -5.379606866992049 -5.213969130412636
-7.242056455058332 -3.92263217337495 -5.121453672656685
-4.360941153958663 -5.132403549095159 -3.2053719168198427
-5.423486827579495 -3.003441914614939 -3.4521178899380516
-4.833650547922218 -5.570039339605273 -5.603540126029429
-6.102691192506313 -6.55325097531329 -4.6937447982987806
-4.149179671722038 -3.5677135697194444]
Unitsdegree_Celsius

The dewpoint is returned in units of degrees Celsius, so convert to Fahrenheit.

dwpf = dwpc.to('degF')

Plot the map

res = '50m'
fig = plt.figure(figsize=(18,12),dpi=150) # Increase the dots per inch from default 100 to make plot easier to read
ax = fig.add_subplot(1,1,1,projection=proj)
ax.set_extent ([lonW,lonE,latS,latN])
ax.set_facecolor(cfeature.COLORS['water'])
ax.add_feature(cfeature.STATES.with_scale(res))
ax.add_feature(cfeature.RIVERS.with_scale(res))
ax.add_feature (cfeature.LAND.with_scale(res))
ax.add_feature(cfeature.COASTLINE.with_scale(res))
ax.add_feature (cfeature.LAKES.with_scale(res))
ax.add_feature (cfeature.STATES.with_scale(res))

stationplot = StationPlot(ax, lons, lats, transform=ccrs.PlateCarree(),
                          fontsize=8)

stationplot.plot_parameter('NW', tmpf, color='red')
stationplot.plot_parameter('SW', dwpf, color='green')
# A more complex example uses a custom formatter to control how the sea-level pressure
# values are plotted. This uses the standard trailing 3-digits of the pressure value
# in tenths of millibars.
stationplot.plot_parameter('NE', slp, color='purple', formatter=lambda v: format(10 * v, '.0f')[-3:])
stationplot.plot_barb(u, v,zorder=2)
plotTitle = f'NYSM Temperature and Dewpoint($^\circ$F), SLP (hPa), Peak 5-min Wind (kts), {titleString}'
ax.set_title (plotTitle);
../../_images/01_Metpy_NYSMMap_50_0.png

Save the plot to the current directory.

figName = f'NYSM_{figString}.png'
figName
'NYSM_20230309_2135.png'
fig.savefig(figName)

Summary

  • The MetPy library provides methods to assign physical units to numerical arrays and perform units-aware calculations

  • MetPy’s StationPlot method offers a customized use of Matplotlib’s Pyplot library to plot several meteorologically-relevant parameters centered about several geo-referenced points.

What’s Next?

In the next notebook, we will plot METAR observations from sites across the world, using a different access method to retrieve the data.