• Python Snacks
  • Posts
  • 4 Python packages for visualizing meteorological data

4 Python packages for visualizing meteorological data

Gain insight to meteorological python packages and how you can leverage them to plot weather products such as radar, ABI, and more.

As we all know, Python is a versatile language that’s used across many industries for a wide array of applications. For instance, Dropbox uses it for their website,

Python is used very heavily in the meteorological industry, as it allows developers to build tools quickly and effectively to process, distribute, ingest, and visualize these large datasets.

To put things into context, the ERA5 hourly climate data is ~18GB. A full day’s worth of this data is ~432GB, which is nearly half a terabyte! Now imagine you have a month’s worth of data saved on disk for 30 days - that’s nearly 12,960GB, or nearly 13TB 🤯

I want to highlight 4 meteorology-specific packages to help work with this data. Each of these packages I have personally used at some point and even leverage a few for my job as-needed.

Article Contents

MetPy

Example of upper air sounding map

MetPy is collection of tools in Python for reading, visualizing, and performing calculations with weather data.

With this package, you can easily visualize skew-t diagrams, hodographs, NEXRAD Level 2/3 files, and perform various calculations. MetPy is developed by the Unidata program at the University Corporation for Atmospheric Research (UCAR).

For instance, creating the above map is relatively straight forward and integrates well with the Python ecosystem with other scientific packages such as Pandas:

from datetime import datetime

import pandas as pd

from metpy.cbook import get_test_data
import metpy.plots as mpplots
from metpy.units import units

# Fetch the data and read it in
data = pd.read_csv(get_test_data('UPA_obs.csv', as_file_obj=False))

# Plotting the Observations
obs = mpplots.PlotObs()
obs.data = data
obs.time = datetime(1993, 3, 14, 0)
obs.level = 500 * units.hPa
obs.fields = ['temperature', 'dewpoint', 'height']
obs.locations = ['NW', 'SW', 'NE']
obs.formats = [None, None, lambda v: format(v, '.0f')[:3]]
obs.vector_field = ('u_wind', 'v_wind')
obs.reduce_points = 0

# Add map features for the particular panel
panel = mpplots.MapPanel()
panel.layout = (1, 1, 1)
panel.area = (-124, -72, 20, 53)
panel.projection = 'lcc'
panel.layers = ['coastline', 'borders', 'states', 'land', 'ocean']
panel.plots = [obs]

# Collecting panels for complete figure
pc = mpplots.PanelContainer()
pc.size = (15, 10)
pc.panels = [panel]

# Showing the results
pc.show()

To get started, visit the documentation and install it using either pip or conda:

# With pip:
pip install metpy

# Or with conda:
conda insrtall -c conda-forge metpy

Tropycal

Example of Hurricane Dorian’s track

Tropycal simplifies the process of retrieving and analyzing tropical cyclone data, both for past storms and in real time. It was developed by Tomer Burg and Sam Lillo in 2019 and has been maintained and improved over the years.

This package is able to read in reanalysis data and operational NHC Best Track data, which can be used to perform climatological, seasonal, and individual storm analysis.

The above map was created using the following script:

import tropycal.tracks as tracks
import datetime as dt

# read in HURTDAT2 dataset
basin = tracks.TrackDataset(basin='north_atlantic',include_btk=False)

# Retrieve an instance of Storm for Hurricane Michael
storm = basin.get_storm(('dorian',2019))
    
# Customize our plot
storm.plot(domain='dynamic_tropical')

To get started with Tropycal, visit the documentation and install it using either pip or conda:

# Pip
pip install tropycal

# Conda
conda install -c conda-forge tropycal

Py-ART

Example of a radar image using Py-ART

Py-ART (Python ARM Radar Toolkit) is a Python module containing a collection of weather radar algorithms and utilities. The main purpose of this package is to easily visualize radar data.

The module is able to read common weather radar formats including Sigment/IRIS, MDV, CF/Radial, UF, and NEXRAD Level 2 archive. This data can also be written to NetCDF files.

The following script produces the above image:

import matplotlib.pyplot as plt
import numpy as np

import pyart
from pyart.testing import get_test_data

# read in the data
file = get_test_data("110635.mdv")
radar = pyart.io.read_mdv(file)

# mask out last 10 gates of each ray, this removes the "ring" around the radar.
radar.fields["reflectivity"]["data"][:, -10:] = np.ma.masked

# exclude masked gates from the gridding
gatefilter = pyart.filters.GateFilter(radar)
gatefilter.exclude_transition()
gatefilter.exclude_masked("reflectivity")

# perform Cartesian mapping, limit to the reflectivity field.
grid = pyart.map.grid_from_radars(
    (radar,),
    gatefilters=(gatefilter,),
    grid_shape=(1, 241, 241),
    grid_limits=((2000, 2000), (-123000.0, 123000.0), (-123000.0, 123000.0)),
    fields=["reflectivity"],
)

# create the plot
fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(grid.fields["reflectivity"]["data"][0], origin="lower")
plt.show()

To get started with Py-ART, visit the documentation and install it from either the source, pip, or conda:

# Pip. Note: it's not `pyart`
pip install arm_pyart

# Conda. Note: it's not `pyart`
conda install -c conda-forge arm_pyart

# From source
git clone https://github.com/ARM-DOE/pyart.git
export RSL_PATH=/path/to/rsl
python setup.py install

wrf-python

Example of plotting WRF output.

If you’re in the business of plotting WRF data, this package may be your go-to tool.

wrf-python is a collection of diagnostic and interpolation routines for use with output from the Weather Research and Forecasting (WRF-ARW) Model.

This package provides over 30 diagnostic calculations, several interpolation routines, and utilities to help with plotting via Cartopy or PyNGL (note: basemap is no longer maintained).

The below code produces the above map, leveraging Cartopy:

from netCDF4 import Dataset
import matplotlib.pyplot as plt
from matplotlib.cm import get_cmap
import cartopy.crs as crs
from cartopy.feature import NaturalEarthFeature

from wrf import (to_np, getvar, smooth2d, get_cartopy, cartopy_xlim, cartopy_ylim, latlon_coords)

# Open the NetCDF file
ncfile = Dataset("wrfout_d01_2016-10-07_00_00_00")

# Get the sea level pressure
slp = getvar(ncfile, "slp")

# Smooth the sea level pressure since it tends to be noisy near the mountains
smooth_slp = smooth2d(slp, 3, cenweight=4)

# Get the latitude and longitude points
lats, lons = latlon_coords(slp)

# Get the cartopy mapping object
cart_proj = get_cartopy(slp)

# Create a figure
fig = plt.figure(figsize=(12,6))

# Set the GeoAxes to the projection used by WRF
ax = plt.axes(projection=cart_proj)

# Download and add the states and coastlines
states = NaturalEarthFeature(
  category="cultural", 
  scale="50m", 
  facecolor="none", 
  name="admin_1_states_provinces_shp")
ax.add_feature(states, linewidth=.5, edgecolor="black")
ax.coastlines('50m', linewidth=0.8)

# Make the contour outlines and filled contours for the smoothed sea level pressure.
plt.contour(
  to_np(lons), 
  to_np(lats), 
  to_np(smooth_slp), 
  10, colors="black", 
  transform=crs.PlateCarree()
)
plt.contourf(
  to_np(lons), 
  to_np(lats), 
  to_np(smooth_slp), 
  10, 
  transform=crs.PlateCarree(), 
  cmap=get_cmap("jet")
)

# Add a color bar
plt.colorbar(ax=ax, shrink=.98)

# Set the map bounds
ax.set_xlim(cartopy_xlim(smooth_slp))
ax.set_ylim(cartopy_ylim(smooth_slp))

ax.gridlines(color="black", linestyle="dotted")
plt.title("Sea Level Pressure (hPa)")
plt.show()

To get started, visit the documentation and install it using conda:

conda install -c conda-forge wrf-python

As mentioned earlier, all of these packages integrate seamlessly into the Python ecosystem, working in tandem with other Python packages, such as:
- Pandas/Geopandas
- xarray
- Dask
- Shapely
- Numpy
- Matplotlib
- NetCDF4
… Plus so many more.

Interested in a Python book? Look no further…

If you’re a Python programmer with an interest in data visualization, I’d highly recommend DeCaria’s book on Python Programming and Visualization for Scientists.

DeCaria was my professor when I was getting my meteorology degree. He taught the Python course in the program. Without his class and his book, I wouldn’t have pursued a career in software.

This book is an excellent reference book for students and researchers, as well as a classroom text.

Here’s why it’s my favorite Python book and why I’m recommending it to you:

  • Beginner and advanced programmer friendly - start at the beginning or jump right in!

  • Diverse number of topics: Basic Python Programming (syntax, data types & structures, file I/O, etc), packages such as NumPy, Pandas, Cartopy, datetime, and so much more,

  • Built for Python 3,

  • Color coded syntax highlighting,

  • Comes with a GitHub with Jupyter Notebooks with all the code samples and data sets.

I wouldn’t promote this book if I know you wouldn’t find value in it. I’m happy to answer any questions, as I own a copy of it; simply respond to this email.

📧 Join the Python Snacks Newsletter! 🐍

Want even more Python-related content that’s useful? Here’s 3 reasons why you should subscribe the Python Snacks newsletter:

  1. Get Ahead in Python with bite-sized Python tips and tricks delivered straight to your inbox, like the one above.

  2. Exclusive Subscriber Perks: Receive a curated selection of up to 6 high-impact Python resources, tips, and exclusive insights with each email.

  3. Get Smarter with Python in under 5 minutes. Your next Python breakthrough could just an email away.

You can unsubscribe at any time.

Interested in starting a newsletter or a blog?

Do you have a wealth of knowledge and insights to share with the world? Starting your own newsletter or blog is an excellent way to establish yourself as an authority in your field, connect with a like-minded community, and open up new opportunities.

If TikTok, Twitter, Facebook, or other social media platforms were to get banned, you’d lose all your followers. This is why you should start a newsletter: you own your audience.

This article may contain affiliate links. Affiliate links come at no cost to you and support the costs of this blog. Should you purchase a product/service from an affiliate link, it will come at no additional cost to you.

Reply

or to participate.