# How to Visualize WeatherNext Predictions: A Complete Guide with Code Examples

> Visualize WeatherNext predictions using xarray.plot, matplotlib, or Cartopy. This guide provides code examples for clear weather data visualization.

- Repository: [Google DeepMind/weathernext](https://github.com/google-deepmind/weathernext)
- Tags: how-to-guide
- Published: 2026-08-10

---

**WeatherNext predictions are returned as `xarray.Dataset` objects, which you can visualize using `xarray.plot`, `matplotlib.pyplot`, or geospatial libraries like Cartopy.**

WeatherNext runs deterministic and generative weather forecasts that output structured data ideal for scientific visualization. The `google-deepmind/weathernext` repository provides a unified predictor interface across multiple model architectures—all returning forecast data in a standard format you can plot immediately.

## Understanding the WeatherNext Prediction Pipeline

### Core Output Format

Every WeatherNext predictor returns an **`xarray.Dataset`** containing forecasted weather variables indexed by time, latitude, longitude, and sample. This design choice allows seamless integration with the scientific Python visualization ecosystem.

In [`weathernext/utils/predictor_base.py`](https://github.com/google-deepmind/weathernext/blob/main/weathernext/utils/predictor_base.py), the abstract `Predictor` base class defines the interface that all models implement. The `__call__` method signature guarantees a consistent return type regardless of underlying architecture.

### From Mesh to Lat-Lon Grid

Many WeatherNext models operate on an **icosahedral mesh** for computational efficiency. The conversion to a regular latitude-longitude grid happens automatically via `_decode_lat_lon_grid_data_from_mesh` in [`weathernext/weathernext2/architecture.py`](https://github.com/google-deepmind/weathernext/blob/main/weathernext/weathernext2/architecture.py). This method handles:

- Mesh node interpolation to a 0.25° or 1.0° lat-lon grid
- Coordinate metadata assignment
- Optional activation function application

The final dataset is ready for plotting without additional transformation.

## Visualizing Predictions with xarray and Matplotlib

WeatherNext declares `matplotlib` as a core dependency in [`setup.py`](https://github.com/google-deepmind/weathernext/blob/main/setup.py), ensuring plotting tools are available. The `xarray.plot` module provides the most direct path from predictions to publication-ready figures.

### Basic Visualization Example

```python
import matplotlib.pyplot as plt
import xarray as xr
import cartopy.crs as ccrs
import cartopy.feature as cfeature

from weathernext.utils import checkpoint
from weathernext.weathernext2.fgn import FGN
from weathernext.utils import predictor_base

# ----------------------------------------------------------------------

# 1️⃣ Load a pretrained model checkpoint

# ----------------------------------------------------------------------

ckpt_path = "gs://weather-forecast/checkpoints/fgn_ckpt_2023"
model = checkpoint.load_checkpoint(ckpt_path)
predictor = model["predictor"]

# ----------------------------------------------------------------------

# 2️⃣ Create or load input data

# ----------------------------------------------------------------------

# Option A: Use dummy inputs for testing

inputs = predictor_base.make_dummy_inputs(predictor, num_samples=1)

# Option B: Load real ERA5 initial conditions

# inputs = xr.open_dataset("era5_2023_01_01.nc")

# ----------------------------------------------------------------------

# 3️⃣ Generate forecast predictions

# ----------------------------------------------------------------------

predictions: xr.Dataset = predictor(inputs)

# predictions contains variables like 't2m', 'u10', 'v10', 'msl', 'tp'

# ----------------------------------------------------------------------

# 4️⃣ Visualize 2-meter temperature with cartopy

# ----------------------------------------------------------------------

fig = plt.figure(figsize=(12, 6))
ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())

t2m = predictions["t2m"].isel(sample=0, time=-1)  # last timestep, first sample

plot = t2m.plot(
    ax=ax,
    transform=ccrs.PlateCarree(),
    cmap="coolwarm",
    vmin=260,
    vmax=310,
    cbar_kwargs={"label": "2-meter temperature (K)"},
)

ax.coastlines(resolution="50m")
ax.add_feature(cfeature.BORDERS, linestyle=":")
ax.set_title("WeatherNext Temperature Forecast (6h lead time)")

plt.tight_layout()
plt.show()

```

### Quick Plot Without Cartopy

For rapid inspection, `xarray.plot` works without geospatial projections:

```python

# Simple lat-lon plot

predictions["msl"].isel(sample=0, time=slice(0, 4)).plot(
    col="time",
    col_wrap=2,
    cmap="viridis",
)

plt.suptitle("Mean Sea Level Pressure Evolution", y=1.02)
plt.show()

```

## Model-Specific Predictor Implementations

WeatherNext provides three primary model architectures. Each inherits from `PredictorBase` and returns the same `xarray.Dataset` format.

| Model | File | Approach | Best For |
|-------|------|----------|----------|
| **FGN** | [`weathernext/weathernext2/fgn.py`](https://github.com/google-deepmind/weathernext/blob/main/weathernext/weathernext2/fgn.py) | Functional generative network with mesh-based representation | Probabilistic forecasting, ensemble generation |
| **GraphCast** | [`weathernext/weathernext1_graph/graphcast.py`](https://github.com/google-deepmind/weathernext/blob/main/weathernext/weathernext1_graph/graphcast.py) | Graph neural network on icosahedral mesh | 10-day deterministic forecasts |
| **GenCast** | [`weathernext/weathernext1_gen/gencast.py`](https://github.com/google-deepmind/weathernext/blob/main/weathernext/weathernext1_gen/gencast.py) | Transformer-based generative model | State-of-the-art ensemble prediction |

All three implement the identical `__call__` interface, so visualization code remains unchanged across models.

## Advanced Visualization Techniques

### Animating Temporal Evolution

Forecast datasets with multiple time steps support animation via `matplotlib.animation`:

```python
import matplotlib.animation as animation

fig, ax = plt.subplots(figsize=(10, 5))

t2m_series = predictions["t2m"].isel(sample=0)
vmin, vmax = t2m_series.min(), t2m_series.max()

def update(frame):
    ax.clear()
    t2m_series.isel(time=frame).plot(
        ax=ax,
        vmin=vmin,
        vmax=vmax,
        cbar_kwargs={"label": "T2M (K)"},
    )
    ax.set_title(f"Lead time: {frame * 6} hours")

ani = animation.FuncAnimation(fig, update, frames=len(t2m_series.time), interval=200)
ani.save("forecast_animation.mp4", writer="ffmpeg")
plt.close()

```

### Comparing Multiple Samples

For probabilistic forecasts with multiple Monte Carlo samples:

```python

# Plot ensemble spread at a single location

point_forecast = predictions["t2m"].sel(latitude=40.7, longitude=-74.0, method="nearest")

fig, axes = plt.subplots(1, 2, figsize=(12, 4))

# All samples as spaghetti plot

point_forecast.plot.line(x="time", ax=axes[0], color="gray", alpha=0.3, add_legend=False)
point_forecast.mean("sample").plot(ax=axes[0], color="red", linewidth=2, label="Ensemble mean")
axes[0].set_title("Ensemble Temperature Forecast: NYC")
axes[0].legend()

# Probability distribution at final time

final_temps = point_forecast.isel(time=-1)
axes[1].hist(final_temps.values, bins=20, edgecolor="black")
axes[1].axvline(final_temps.mean(), color="red", linestyle="--", label="Mean")
axes[1].set_xlabel("Temperature (K)")
axes[1].set_title("Distribution at final lead time")

plt.tight_layout()
plt.show()

```

## Key Source Files for Visualization

| File | Purpose | Direct Link |
|------|---------|-------------|
| [`weathernext/weathernext2/fgn.py`](https://github.com/google-deepmind/weathernext/blob/main/weathernext/weathernext2/fgn.py) | Main FGN predictor with `__call__` returning `xr.Dataset` | [View source](https://github.com/google-deepmind/weathernext/blob/main/weathernext/weathernext2/fgn.py) |
| [`weathernext/weathernext2/architecture.py`](https://github.com/google-deepmind/weathernext/blob/main/weathernext/weathernext2/architecture.py) | Mesh decoding and post-processing utilities | [View source](https://github.com/google-deepmind/weathernext/blob/main/weathernext/weathernext2/architecture.py) |
| [`weathernext/utils/predictor_base.py`](https://github.com/google-deepmind/weathernext/blob/main/weathernext/utils/predictor_base.py) | Abstract base class and `make_dummy_inputs` helper | [View source](https://github.com/google-deepmind/weathernext/blob/main/weathernext/utils/predictor_base.py) |
| [`weathernext/utils/checkpoint.py`](https://github.com/google-deepmind/weathernext/blob/main/weathernext/utils/checkpoint.py) | Checkpoint loading from GCS or local paths | [View source](https://github.com/google-deepmind/weathernext/blob/main/weathernext/utils/checkpoint.py) |
| [`setup.py`](https://github.com/google-deepmind/weathernext/blob/main/setup.py) | Package dependencies including `matplotlib` | [View source](https://github.com/google-deepmind/weathernext/blob/main/setup.py) |

## Summary

- **WeatherNext predictions** are `xarray.Dataset` objects readable by any scientific Python visualization tool.

- **Three model architectures** (FGN, GraphCast, GenCast) share identical output formats through the `PredictorBase` interface.

- **Mesh-to-grid conversion** happens automatically in [`architecture.py`](https://github.com/google-deepmind/weathernext/blob/main/architecture.py), yielding lat-lon coordinates ready for mapping.

- **Recommended workflow**: Load checkpoint → run `predictor(inputs)` → select variables with `isel`/`sel` → plot with `xarray.plot` or `cartopy`.

- **Key utilities**: `make_dummy_inputs` for testing, `checkpoint.load_checkpoint` for model restoration.

## Frequently Asked Questions

### What plotting libraries work best with WeatherNext outputs?

**Any library compatible with `xarray.Dataset` works.** The repository explicitly depends on `matplotlib`. For geospatial visualization, combine `xarray` with `cartopy` or `hvplot`. The `xarray.plot` submodule provides the fastest path to inspect forecasts without additional dependencies.

### How do I handle probabilistic forecasts with multiple samples?

**Use the `sample` dimension for ensemble analysis.** Select individual samples with `.isel(sample=n)`, compute statistics across `.mean("sample")` or `.std("sample")`, or plot all samples as a spaghetti plot. The dataset structure treats samples identically to time or spatial dimensions.

### Can I visualize predictions directly on the icosahedral mesh?

**Yes, though lat-lon grids are preferred.** The raw mesh output (before `_decode_lat_lon_grid_data_from_mesh`) contains node coordinates in `face_lon` and `face_lat` variables. You can plot these using triangulation-based methods in `matplotlib.tricontourf` or specialized tools like `mpl_toolkits.basemap`, but standard workflows use the decoded grid.

### Where do I find pretrained checkpoints to visualize?

**Checkpoints are distributed separately from code.** The [`checkpoint.py`](https://github.com/google-deepmind/weathernext/blob/main/checkpoint.py) utility supports Google Cloud Storage (`gs://`) paths and local filesystems. Refer to the official WeatherNext documentation or model cards for specific checkpoint locations. The loading API (`checkpoint.load_checkpoint`) handles both sources transparently.