🚀 Jumpstart 2027: Custom, Secure AI Workflows to Adopt Now. Reserve your spot →

Chris Parmer

Chris Parmer

2026-11-16

xarray demo

Multidimensional and gridded data in Python, with Dash and Plotly

TL;DR

  • xarray is the Python package for labeled multi-dimensional arrays, such as weather, climate, ocean and satellite grids with time, latitude and longitude, read from NetCDF or Zarr files. Stephan Hoyer, Alex Kleeman and Eugene Brevdo wrote it as "xray" at The Climate Corporation and released it as open source in May 2014.
  • Coding agents know it well. You describe the analysis in plain words and name a few xarray functions, and the agent writes the sel, groupby and resample code.
  • This demo shows what's possible through Site Scout, a Dash app for screening wind and solar sites, built on 26 years of daily NASA data on two different grids.
  • The current release, 2026.9.0 (September 29, 2026), lets apply_ufunc run on a whole DataTree, which Site Scout uses to compute one statistic on both grids in a single call.

What is xarray?

Energy, agriculture, insurance, ocean and climate teams all work with gridded data: a value for every cell of a map at every hour or day, often for decades. NumPy can hold those arrays, but you have to remember which axis is time and which is latitude, and turn dates into index positions yourself.

xarray puts names and coordinates on the dimensions, so you write ds.sel(lat=32.5, lon=-100.6, method="nearest") instead of arr[:, 13, 5], and ds.groupby("time.month").mean() for a monthly climatology. A DataTree keeps several datasets on different grids in one object. That makes xarray the package for Dash apps built on maps and time series of gridded data, for example:

  • wind, solar and hydropower resource screening;
  • heating and cooling demand from gridded temperature;
  • weather and climate exposure for a portfolio of sites;
  • crop, water and vegetation monitoring from satellites;
  • ocean temperature and model output in research.

These demos show you what's possible, and a coding agent writes the code. The rest of this post is one app we built that way, the prompts for each page, and the xarray capabilities worth naming in them. It's one of the apps in our guide to Python packages for data.

How to load NetCDF data with xarray

NASA's Prediction Of Worldwide Energy Resources (POWER) project serves daily weather and solar data through a free API. We downloaded a 10° by 10° box centered on Texas from 2001 to November 2026 as NetCDF files: wind speed at 50 m from NASA's Modern-Era Retrospective analysis for Research and Applications (MERRA-2) reanalysis, and the sunlight reaching the ground from NASA's Clouds and the Earth's Radiant Energy System (CERES) satellites.

The two variables come on different grids, which is common with gridded data, so we kept each on its own grid in one DataTree and stored it as compressed 16-bit integers.

Prompt: Download daily data from the NASA POWER regional API (power.larc.nasa.gov/api/temporal/daily/regional, community=RE, format=NETCDF) for longitude -104 to -94 and latitude 26 to 36, 2001 to today: WS50M and ALLSKY_SFC_SW_DWN, one parameter and one year per request. Open them with xarray open_mfdataset, keep each variable on its own grid in an xr.DataTree (/wind and /solar), and save it with to_netcdf using int16 encoding with a scale_factor and zlib compression.

Demo App: Site Scout

Site Scout has three pages: a resource map, a report for the chosen site, and a page on how 2026 compares with the 2001 to 2025 normal. Every chart is computed with xarray in a Dash callback.

Resource map: long-term averages on a grid

Site Scout resource map: average daily wind speed at 50 m from 2001 to 2025 in 336 grid cells over Texas, strongest in the Panhandle, with Sweetwater selected and a table of the highest cells

The map shows the 2001 to 2025 average for each grid cell, for wind or solar, with the strongest cells listed beside it. Clicking a cell picks the site for the other pages, which is how a developer would shortlist locations before ordering detailed studies.

Prompt: Build a Dash app called Site Scout with Plotly maps. Load the DataTree once at startup with xr.open_datatree. On a "Resource map" tab, draw each grid cell as a square polygon on a Choroplethmap (carto-positron), colored by the 2001-2025 mean (ds.sel(time=slice("2001","2025")) .mean("time")). Let me switch between wind and solar, show the top cells in a table, and make a click on a cell select the site (store its lat and lon in a dcc.Store).

Site report: monthly climatology and percentiles

Site Scout site report for Sweetwater: average wind 7.07 m/s, solar 5.28 kWh per square meter per day, windiest month April, monthly wind and solar charts with a band for the middle 80% of years and 2026 in pink, and annual mean wind for 2001 to 2025 with P50 and P90 lines

The site report pulls the nearest cell from each grid and shows how the resource varies by month and from year to year, with a band for the middle 80% of years and the current year on top. The annual chart marks P50 and P90, the levels a site beats in half the years and in nine years out of 10, the convention used in energy yield assessments.

Prompt: Add a "Site report" tab for the selected site. Pick the nearest cell in each grid with .sel(lat=..., lon=..., method="nearest"). Compute monthly means per year with resample(time="MS").mean(), then groupby("time.month").quantile([0.1, 0.5, 0.9]) for a P10-P90 band and median, and overlay 2026. Add a bar chart of annual means (resample(time="YE")) with P50 and P90 lines, and KPI cards: averages, windiest and calmest month, and the correlation of daily anomalies (groupby("time.dayofyear") minus its mean, then xr.corr).

2026 so far: anomalies against the normal

Site Scout map of 2026 wind from January 1 to November 13 against the same days in 2001 to 2025: most cells are blue, below normal, down to minus 9.8 percent in the southwest

The same map can show this year against the normal for the same calendar days, cell by cell. In 2026 most of the region has been a little less windy than usual, about 2.4% below normal on average, which matters to anyone comparing a wind farm's output with its forecast.

Prompt: Add a "2026 so far vs normal" option to the map: 2026 mean divided by the 2001-2025 mean of the same calendar days (filter with time.dt.dayofyear <= today's day of year), as a percent, on a blue-white-pink diverging scale centered on zero. Use xr.map_over_datasets so the same function runs on the wind and solar nodes of the DataTree.

Low-resource streaks: your own function with apply_ufunc

Site Scout map of the longest run of consecutive days in the bottom 10 percent for solar in each 1 degree cell, from 6 to 13 days, with a table of the longest streaks

Averages hide runs of calm or cloudy days, and those runs decide how much storage and backup a site needs. This map shows, for each cell, the longest stretch of consecutive days in the bottom 10% of that cell's own history.

It's the one place we show code, because it uses the release's headline feature: apply_ufunc takes the whole DataTree and returns a tree with the same structure, so a plain Python function runs on every cell of both grids in one call.

def longest_run(x):
best = cur = 0
for v in x:
cur = cur + 1 if v else 0
best = max(best, cur)
return best
low = xr.map_over_datasets(lambda d: d < d.quantile(0.1, dim="time").drop_vars("quantile") if d.data_vars else d, base)
streaks = xr.apply_ufunc(longest_run, low, input_core_dims=[["time"]], vectorize=True) # DataTree in, DataTree out

Prompt: Add a "Longest low-resource streak" option: for each cell, flag days below that cell's own 2001-2025 10th percentile, then run a plain Python longest-run function along time with xr.apply_ufunc(..., input_core_dims=[["time"]], vectorize=True) on the whole DataTree.

2026 over time: area-weighted averages

Site Scout 2026 page: Texas-wide wind and solar as a percent of normal, smoothed over 30 days, and month-by-month 2026 bars for Sweetwater, with November wind down 26.6 percent

The last page tracks the whole region day by day against its normal, weighted by the cosine of latitude because grid cells shrink toward the poles, and smoothed over 30 days. Below it, bars compare each month of 2026 with the normal at the selected site.

Prompt: Add a "2026 so far" tab. For each variable, compute a daily climatology with groupby("time.dayofyear").mean() over 2001-2025, smooth it with rolling(dayofyear=31, center=True), subtract it from 2026, and take the area-weighted mean with .weighted(np.cos(np.deg2rad(lat))). Smooth with rolling(time=30) and plot both lines. Below it, grouped bars of each 2026 month vs the same month's 2001-2025 mean at the selected site.

What's possible

These are the xarray capabilities to name when you ask an agent for a gridded-data app:

  • Open many files as one dataset: xr.open_mfdataset("data/*.nc"), and xr.open_zarr for cloud stores.
  • Select by label, not position: sel(lat=..., lon=..., method="nearest") for a point, sel(time=slice("2001", "2025")) for a period.
  • Seasonal and monthly patterns: groupby("time.month"), groupby("time.dayofyear") and groupby("time.season").
  • Change the time step: resample(time="MS") or resample(time="YE") for monthly and yearly means.
  • Moving windows: rolling(time=30).mean().
  • Area averages: weighted(np.cos(np.deg2rad(ds.lat))).mean(["lat", "lon"]).
  • Percentiles and correlations: quantile([0.1, 0.5, 0.9], dim="time") and xr.corr(a, b).
  • Your own function on every cell: xr.apply_ufunc(func, da, input_core_dims=[["time"]], vectorize=True).
  • Several grids in one object: xr.DataTree, with xr.map_over_datasets to run a function on every node.
  • Compact files: to_netcdf with an int16 scale_factor and zlib=True.

Other apps you can build with xarray

  • Energy: a hydropower inflow outlook from gridded precipitation and snow, using resample and anomalies against a climatology.
  • Energy: a heating and cooling degree day tracker for gas and power demand, from gridded temperature grouped by region.
  • Finance and insurance: a weather exposure map for a portfolio's sites, with sel(method="nearest") at each site and quantile for return levels. Our geopandas demo covers the site and region side of the same app.
  • Pharma: a heat and humidity profile for clinical trial sites and drug storage, with groupby("time.season") at each site.
  • Agriculture: a crop condition monitor on satellite vegetation index grids, with rolling and anomalies against a 20-year normal.
  • Ocean science: a sea surface temperature explorer from NOAA's daily optimum interpolation dataset (OISST), with groupby("time.season") and polyfit for trends.

What's new in xarray 2026.9.0

xarray 2026.9.0 came out on September 29, 2026, from 45 contributors:

  • apply_ufunc accepts DataTree inputs and returns a tree with the same structure. Site Scout uses it for the streak maps.
  • DataArray has the Arrow PyCapsule interface, for near zero-copy export to pyarrow, polars or DuckDB.
  • A new DataArray.plot.lines() method, and flox-accelerated groupby medians.
  • Read support for Zarr V3 arrays with variable-sized chunks.
  • Bottleneck is off by default, because some of its operations are less numerically stable than NumPy's, and xr.set_options(use_bottleneck=True) turns it back on. This is the last release to support Python 3.11.

Running xarray apps on Plotly Cloud and Dash Enterprise

We deployed Site Scout privately to Plotly Cloud, and the same applies on Dash Enterprise:

  • Ship a compact file, not raw downloads. 52 yearly NetCDF files became one 6.1 MB DataTree with int16 encoding.
  • Load into memory once at startup with .load() after open_datatree, so every callback is a NumPy operation, and precompute the maps that don't depend on the user.
  • List what xarray calls behind the scenes in requirements.txt. Our first deploy failed because interp imports SciPy, which wasn't installed. Both series were daily, so xr.align(a, b, join="inner") matched them without interpolating.

FAQ

bluesly
x
instagram
youtube
medium
fcaebook

Product

© 2026
Plotly. All rights reserved.
Cookie Preferences
aicpa/soc2