Comprehensive Python library for meteorological data analysis and weather visualization.
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
MetPy provides a comprehensive plotting system designed specifically for atmospheric science visualization. It includes specialized meteorological diagrams like Skew-T log-P plots and hodographs, station model plotting, and a declarative plotting framework for creating publication-quality meteorological visualizations.
Professional-quality atmospheric soundings and analysis diagrams used in operational meteorology and research.
class SkewT:
"""
Create Skew-T log-P diagrams for atmospheric sounding analysis.
The Skew-T log-P diagram is the standard tool for analyzing atmospheric
vertical structure, stability, and thermodynamic processes.
"""
def __init__(self, fig=None, rotation=30, aspect=75):
"""
Initialize a Skew-T log-P diagram.
Parameters:
- fig: matplotlib Figure object (optional)
- rotation: skew angle in degrees
- aspect: aspect ratio
"""
def plot(self, pressure, temperature, *args, **kwargs):
"""
Plot temperature profile.
Parameters:
- pressure: pressure levels
- temperature: temperature values
- args, kwargs: additional plot arguments
Returns:
Matplotlib line objects
"""
def plot_dry_adiabats(self, t0=None, pressure=None, **kwargs):
"""
Plot dry adiabatic lines.
Parameters:
- t0: starting temperatures
- pressure: pressure range
- kwargs: plot styling options
"""
def plot_moist_adiabats(self, t0=None, pressure=None, **kwargs):
"""
Plot moist adiabatic lines.
Parameters:
- t0: starting temperatures
- pressure: pressure range
- kwargs: plot styling options
"""
def plot_mixing_lines(self, mixing_ratio=None, pressure=None, **kwargs):
"""
Plot constant mixing ratio lines.
Parameters:
- mixing_ratio: mixing ratio values
- pressure: pressure range
- kwargs: plot styling options
"""
def shade_area(self, pressure, temperature1, temperature2=None, **kwargs):
"""
Shade area between temperature profiles.
Parameters:
- pressure: pressure levels
- temperature1: first temperature profile
- temperature2: second temperature profile (optional)
- kwargs: shading options
"""
def shade_cape(self, pressure, temperature, dewpoint, parcel_path=None, **kwargs):
"""
Shade CAPE (Convective Available Potential Energy) area.
Parameters:
- pressure: pressure profile
- temperature: environmental temperature
- dewpoint: dewpoint temperature
- parcel_path: parcel temperature profile
- kwargs: shading options
"""
def shade_cin(self, pressure, temperature, dewpoint, parcel_path=None, **kwargs):
"""
Shade CIN (Convective Inhibition) area.
Parameters:
- pressure: pressure profile
- temperature: environmental temperature
- dewpoint: dewpoint temperature
- parcel_path: parcel temperature profile
- kwargs: shading options
"""
class Hodograph:
"""
Create hodograph diagrams for wind shear analysis.
Hodographs display wind vector changes with height and are essential
for analyzing wind shear and storm motion.
"""
def __init__(self, ax=None, component_range=80):
"""
Initialize hodograph plot.
Parameters:
- ax: matplotlib Axes object (optional)
- component_range: range for u and v components
"""
def add_grid(self, increment=10, **kwargs):
"""
Add range rings and radial lines to hodograph.
Parameters:
- increment: spacing between range rings
- kwargs: grid styling options
"""
def plot(self, u, v, **kwargs):
"""
Plot wind hodograph.
Parameters:
- u: u-component of wind
- v: v-component of wind
- kwargs: plot styling options
Returns:
Matplotlib line objects
"""
def plot_colormapped(self, u, v, colors, **kwargs):
"""
Plot hodograph with color mapping.
Parameters:
- u: u-component of wind
- v: v-component of wind
- colors: color values for each point
- kwargs: plot and colormap options
"""
def wind_vectors(self, u, v, **kwargs):
"""
Plot wind vectors on hodograph.
Parameters:
- u: u-component of wind
- v: v-component of wind
- kwargs: vector plot options
"""
class StationPlot:
"""
Create station model plots for surface observations.
Station plots display multiple meteorological parameters at observation
locations using standard WMO symbology and layout conventions.
"""
def __init__(self, ax, x, y, fontsize=10, spacing=None, transform=None):
"""
Initialize station plot.
Parameters:
- ax: matplotlib Axes object
- x: x-coordinates of stations
- y: y-coordinates of stations
- fontsize: text font size
- spacing: minimum spacing between stations
- transform: coordinate transformation
"""
def plot_parameter(self, location, parameter, **kwargs):
"""
Plot parameter at specified location around station.
Parameters:
- location: location code ('NW', 'N', 'NE', 'W', 'C', 'E', 'SW', 'S', 'SE')
- parameter: parameter values to plot
- kwargs: text formatting options
"""
def plot_symbol(self, location, codes, symbol_mapper, **kwargs):
"""
Plot symbols using code mapping.
Parameters:
- location: location around station
- codes: symbol codes
- symbol_mapper: code to symbol mapping
- kwargs: symbol formatting options
"""
def plot_barb(self, u, v, **kwargs):
"""
Plot wind barbs at station locations.
Parameters:
- u: u-component of wind
- v: v-component of wind
- kwargs: barb formatting options
"""
def plot_text(self, location, text, **kwargs):
"""
Plot text at station locations.
Parameters:
- location: text location around station
- text: text values
- kwargs: text formatting options
"""High-level plotting system for creating complex meteorological visualizations with minimal code.
class MapPanel:
"""
Configure map panel for meteorological plotting.
Provides map projection, geographic boundaries, and cartographic
features for meteorological data visualization.
"""
def __init__(self, **kwargs):
"""
Initialize map panel.
Parameters:
- projection: map projection ('lcc', 'merc', 'stere', etc.)
- area: geographic area ('us', 'conus', custom bounds)
- layers: cartographic layers to include
- title: panel title
"""
class ImagePlot:
"""
Plot raster/image data on maps.
For displaying satellite imagery, radar data, and gridded
meteorological fields as continuous images.
"""
def __init__(self, **kwargs):
"""
Initialize image plot.
Parameters:
- field: data field to plot
- colormap: colormap name or object
- image_range: data range for color scaling
- colorbar: colorbar configuration
"""
class ContourPlot:
"""
Create contour plots of meteorological fields.
For plotting isopleths of pressure, temperature, geopotential
height, and other continuous meteorological variables.
"""
def __init__(self, **kwargs):
"""
Initialize contour plot.
Parameters:
- field: data field to contour
- level: vertical level or pressure
- contours: contour levels or interval
- clabels: contour label configuration
- linecolor: contour line color
- linestyle: contour line style
"""
class FilledContourPlot:
"""
Create filled contour plots.
For displaying continuous meteorological fields with
color-filled regions between contour levels.
"""
def __init__(self, **kwargs):
"""
Initialize filled contour plot.
Parameters:
- field: data field to plot
- level: vertical level
- contours: contour levels
- colormap: colormap for filling
- colorbar: colorbar configuration
"""
class BarbPlot:
"""
Plot wind barbs on meteorological maps.
Standard meteorological wind barbs showing wind speed
and direction using conventional symbology.
"""
def __init__(self, **kwargs):
"""
Initialize wind barb plot.
Parameters:
- field: wind field (u, v components or speed/direction)
- level: vertical level
- skip: barb spacing/thinning
- scale: barb size scaling
- earth_relative: wind reference frame
"""
class ArrowPlot:
"""
Plot vector arrows for wind or other vector fields.
Vector arrows for displaying wind, storm motion,
or other meteorological vector quantities.
"""
def __init__(self, **kwargs):
"""
Initialize arrow plot.
Parameters:
- field: vector field data
- level: vertical level
- skip: arrow spacing
- scale: arrow size scaling
- pivot: arrow pivot point
"""
class PlotObs:
"""
Plot point observations on maps.
For displaying surface observations, upper-air data,
and other point-based meteorological measurements.
"""
def __init__(self, **kwargs):
"""
Initialize observation plot.
Parameters:
- data: observation data
- fields: fields to plot
- locations: parameter locations on station model
- time: observation time
- level: vertical level (for upper-air)
"""
class PanelContainer:
"""
Container for organizing multiple map panels.
Manages layout and arrangement of multiple meteorological
plots in publication-quality figure layouts.
"""
def __init__(self, **kwargs):
"""
Initialize panel container.
Parameters:
- panel_size: size of individual panels
- ncols: number of columns
- hspace: horizontal spacing
- vspace: vertical spacing
"""
def add_panel(self, panel, **kwargs):
"""
Add panel to container.
Parameters:
- panel: MapPanel object to add
- kwargs: panel-specific options
"""
def add_plot(self, panel_num, plot, **kwargs):
"""
Add plot to specific panel.
Parameters:
- panel_num: panel number (0-indexed)
- plot: plot object to add
- kwargs: plot-specific options
"""
def show(self, **kwargs):
"""
Display the complete figure.
Parameters:
- kwargs: figure display options
"""
def save(self, filename, **kwargs):
"""
Save figure to file.
Parameters:
- filename: output filename
- kwargs: save options (dpi, format, etc.)
"""Meteorological color tables and styling utilities.
def colortables():
"""
Access meteorological colormaps and color tables.
Returns:
Dictionary of available color tables for meteorological parameters
"""
# Available meteorological colormaps
meteorological_colormaps = {
'precipitation': 'precipitation colormap for rainfall/snowfall',
'temperature': 'temperature colormap for thermal fields',
'reflectivity': 'radar reflectivity colormap',
'velocity': 'doppler velocity colormap',
'ir_enhanced': 'enhanced infrared satellite colormap'
}from metpy.plots import SkewT
from metpy.units import units
import matplotlib.pyplot as plt
import numpy as np
# Sample sounding data
pressure = np.array([1000, 925, 850, 700, 500, 400, 300, 250, 200]) * units.hPa
temperature = np.array([20, 15, 10, 0, -15, -25, -35, -45, -55]) * units.celsius
dewpoint = np.array([15, 10, 5, -5, -20, -30, -40, -50, -60]) * units.celsius
# Create Skew-T plot
fig = plt.figure(figsize=(10, 8))
skew = SkewT(fig=fig)
# Plot temperature and dewpoint profiles
skew.plot(pressure, temperature, 'r-', linewidth=2, label='Temperature')
skew.plot(pressure, dewpoint, 'g-', linewidth=2, label='Dewpoint')
# Add atmospheric lines
skew.plot_dry_adiabats(color='gray', alpha=0.5)
skew.plot_moist_adiabats(color='blue', alpha=0.5)
skew.plot_mixing_lines(color='green', alpha=0.5)
# Calculate and plot parcel profile
parcel_prof = mpcalc.parcel_profile(pressure, temperature[0], dewpoint[0])
skew.plot(pressure, parcel_prof, 'k--', label='Parcel Path')
# Shade CAPE and CIN areas
skew.shade_cape(pressure, temperature, dewpoint)
skew.shade_cin(pressure, temperature, dewpoint)
plt.legend()
plt.title('Atmospheric Sounding Analysis')
plt.show()from metpy.plots import Hodograph
import matplotlib.pyplot as plt
# Sample wind data
heights = np.array([0, 1, 2, 3, 6, 9, 12]) * units.km
u_wind = np.array([5, 10, 15, 20, 25, 15, 10]) * units('m/s')
v_wind = np.array([0, 5, 10, 15, 20, 25, 20]) * units('m/s')
# Create hodograph
fig, ax = plt.subplots(figsize=(8, 8))
hodo = Hodograph(ax=ax, component_range=60)
# Add grid
hodo.add_grid(increment=10)
# Plot wind hodograph with height coloring
l = hodo.plot_colormapped(u_wind, v_wind, heights.m, cmap='viridis')
plt.colorbar(l, label='Height (km)')
# Add wind speed rings
for speed in [10, 20, 30, 40]:
circle = plt.Circle((0, 0), speed, fill=False, linestyle='--', alpha=0.5)
ax.add_patch(circle)
plt.title('Wind Hodograph')
plt.show()from metpy.plots import MapPanel, ContourPlot, BarbPlot, PanelContainer
from metpy.io import parse_metar_to_dataframe
# Load surface observations
df = parse_metar_to_dataframe('surface_obs.txt')
# Create map panel
panel = MapPanel(projection='lcc', area='us',
layers=['coastline', 'borders', 'states'])
# Add pressure contours
contour = ContourPlot(field='sea_level_pressure',
contours=range(980, 1040, 4),
clabels=True)
# Add wind barbs
barbs = BarbPlot(field=['u_wind', 'v_wind'],
skip=2, scale=0.8)
# Create figure
pc = PanelContainer(panel_size=(12, 8))
pc.add_panel(panel)
pc.add_plot(0, contour)
pc.add_plot(0, barbs)
pc.show()from metpy.plots import StationPlot
import matplotlib.pyplot as plt
# Sample station data
x = [-100, -95, -90, -85] # Longitude
y = [35, 40, 45, 50] # Latitude
temp = [75, 68, 62, 55] # Temperature (F)
pressure = [1013, 1015, 1018, 1020] # Pressure (hPa)
# Create map
fig, ax = plt.subplots(figsize=(10, 8), subplot_kw=dict(projection=ccrs.PlateCarree()))
ax.add_feature(cfeature.COASTLINE)
ax.add_feature(cfeature.BORDERS)
ax.add_feature(cfeature.STATES)
# Create station plot
stationplot = StationPlot(ax, x, y, fontsize=12, transform=ccrs.PlateCarree())
# Plot temperature in upper-left position
stationplot.plot_parameter('NW', temp, color='red')
# Plot pressure in upper-right position
stationplot.plot_parameter('NE', pressure, color='blue')
# Add wind barbs
u_wind = [5, -3, 8, -10]
v_wind = [10, 15, -5, 12]
stationplot.plot_barb(u_wind, v_wind)
plt.title('Surface Station Plot')
plt.show()Plotting tools integrate seamlessly with MetPy's I/O and calculation functions.
from metpy.io import GempakSurface
from metpy.plots import SkewT
import metpy.calc as mpcalc
# Read sounding data
sf = GempakSurface('upper_air.gem')
sounding = sf.gdxarray(station_id='KDEN')
# Extract profiles
pressure = sounding['PRES']
temperature = sounding['TEMP']
dewpoint = sounding['DWPT']
# Calculate derived quantities
parcel_profile = mpcalc.parcel_profile(pressure, temperature[0], dewpoint[0])
cape, cin = mpcalc.cape_cin(pressure, temperature, dewpoint, parcel_profile)
# Create comprehensive Skew-T plot
skew = SkewT()
skew.plot(pressure, temperature, 'r-', label='Temperature')
skew.plot(pressure, dewpoint, 'g-', label='Dewpoint')
skew.plot(pressure, parcel_profile, 'k--', label='Parcel')
skew.shade_cape(pressure, temperature, dewpoint)
skew.shade_cin(pressure, temperature, dewpoint)
plt.title(f'CAPE: {cape:.0f} J/kg, CIN: {cin:.0f} J/kg')from typing import Optional, Union, Sequence, Dict, Any
import matplotlib.pyplot as plt
import matplotlib.axes as axes
import numpy as np
from pint import Quantity
# Plot object types
SkewTPlot = SkewT
HodographPlot = Hodograph
StationModelPlot = StationPlot
# Data types for plotting
PlotData = Union[np.ndarray, Quantity, Sequence]
ColorMap = Union[str, plt.cm.ColorMap]
PlotAxes = Union[axes.Axes, axes.GeoAxes]
# Configuration types
PlotConfig = Dict[str, Any]
PanelConfig = Dict[str, Any]