Skip to content

Minute-by-minute precipitation charts

Choose one of three short Python examples. Each script requests a forecast, displays one chart, and saves one JPG.

Precipitation Nowcast API · API reference

Keep your API key on the server

We do not recommend putting API keys in frontend code. Run these examples locally or on your server. Each reads the key from an environment variable and sends it in a request header.

Setup

Install the dependencies and set your key from Getting started:

Bash
python -m pip install requests numpy "matplotlib>=3.6"
export RAINBOW_API_KEY='YOUR_API_KEY'

In Windows PowerShell, use $env:RAINBOW_API_KEY='YOUR_API_KEY' instead of export.

Choose a tab below, save its complete code under the shown filename, and replace LON and LAT with your location. Each example runs independently.

Choose a chart

Minute-by-minute precipitation forecast shown as a blue line with light shading

View the available forecast, up to four hours ahead. Straight segments connect the original minute values without smoothing or extra forecast points. Missing intervals break the line.

chart.py
import os
from datetime import datetime, timezone

import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import requests

LON, LAT = 16.0, 46.0  # Replace with your location.

# Request the forecast from the API.
# Keep the key on your server or local machine, never in frontend code.
response = requests.get(
    f"https://api.rainbow.ai/nowcast/v1/precip-global/{LON}/{LAT}",
    headers={"Ocp-Apim-Subscription-Key": os.environ["RAINBOW_API_KEY"]},
    timeout=15,
)
response.raise_for_status()

# Prepare the minute-by-minute data.
forecast = sorted(
    response.json()["forecast"],
    key=lambda row: row["timestampBegin"],
)
if not forecast:
    raise ValueError("No forecast available for this location.")
if any(row["timestampEnd"] - row["timestampBegin"] != 60 for row in forecast):
    raise ValueError("Expected one-minute forecast intervals.")

times, rates = [], []
for i, row in enumerate(forecast):
    if i and row["timestampBegin"] != forecast[i - 1]["timestampEnd"]:
        times.append(
            datetime.fromtimestamp(forecast[i - 1]["timestampEnd"], timezone.utc)
        )
        rates.append(float("nan"))  # Leave missing minutes blank.
    times.append(datetime.fromtimestamp(row["timestampBegin"], timezone.utc))
    rates.append(row["precipRate"])

end = datetime.fromtimestamp(forecast[-1]["timestampEnd"], timezone.utc)
peak = max(row["precipRate"] for row in forecast)

# Draw the chart.
plt.style.use("seaborn-v0_8-whitegrid")
fig, ax = plt.subplots(figsize=(10, 4), dpi=160, layout="constrained")
ax.plot(times, rates, color="#4B7BEB", linewidth=2)
ax.scatter(times, rates, color="#4B7BEB", s=1)
ax.fill_between(times, rates, color="#4B7BEB", alpha=0.10)
ax.set(
    title="Precipitation forecast",
    xlabel="Time (UTC)",
    ylabel="Rate (mm/h)",
    xlim=(times[0], end),
    ylim=(0, max(0.1, peak * 1.15)),
)
ax.xaxis.set_major_locator(
    mdates.AutoDateLocator(minticks=3, maxticks=5, tz=timezone.utc)
)
ax.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M", tz=timezone.utc))

# Save and display the chart.
fig.savefig("nowcast-chart.jpg", pil_kwargs={"quality": 94, "optimize": True})
plt.show()

Run:

Bash
python chart.py

Displays the chart and saves nowcast-chart.jpg.

Precipitation forecast for the first hour shown as individual blue minute bars

View the first 60 minutes of the forecast, with one bar per minute. Missing intervals leave gaps; zero precipitation stays zero.

hour_bars.py
import os
from datetime import datetime, timedelta, timezone

import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import requests

LON, LAT = 16.0, 46.0  # Replace with your location.

# Request the forecast from the API.
# Keep the key on your server or local machine, never in frontend code.
response = requests.get(
    f"https://api.rainbow.ai/nowcast/v1/precip-global/{LON}/{LAT}",
    headers={"Ocp-Apim-Subscription-Key": os.environ["RAINBOW_API_KEY"]},
    timeout=15,
)
response.raise_for_status()

# Prepare the next-hour data.
forecast = sorted(
    response.json()["forecast"],
    key=lambda row: row["timestampBegin"],
)
if not forecast:
    raise ValueError("No forecast available for this location.")
if any(row["timestampEnd"] - row["timestampBegin"] != 60 for row in forecast):
    raise ValueError("Expected one-minute forecast intervals.")

start = forecast[0]["timestampBegin"]
end = min(start + 3600, forecast[-1]["timestampEnd"])
hour = [row for row in forecast if row["timestampBegin"] < end]
times = [datetime.fromtimestamp(row["timestampBegin"], timezone.utc) for row in hour]
rates = [row["precipRate"] for row in hour]

# Draw the chart.
plt.style.use("seaborn-v0_8-whitegrid")
fig, ax = plt.subplots(figsize=(10, 4), dpi=160, layout="constrained")
ax.bar(times, rates, width=timedelta(seconds=45), align="edge", color="#6694F0")
ax.set(
    title="Next hour · one bar per minute",
    xlabel="Time (UTC)",
    ylabel="Rate (mm/h)",
    xlim=(times[0], datetime.fromtimestamp(end, timezone.utc)),
    ylim=(0, max(0.1, max(rates) * 1.15)),
)
ax.xaxis.set_major_locator(
    mdates.MinuteLocator(byminute=[0, 15, 30, 45], tz=timezone.utc)
)
ax.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M", tz=timezone.utc))

# Save and display the chart.
fig.savefig("nowcast-hour-bars.jpg", pil_kwargs={"quality": 94, "optimize": True})
plt.show()

Run:

Bash
python hour_bars.py

Displays the chart and saves nowcast-hour-bars.jpg.

Minute-by-minute precipitation intensity shown as a blue strip with a numeric mm/h color scale

View the full forecast as one-minute cells. Darker blue means a higher precipitation rate, with a numeric mm/h scale. Missing intervals stay blank; zero rates remain zero.

intensity_strip.py
import os
from datetime import datetime, timezone

import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import numpy as np
import requests

LON, LAT = 16.0, 46.0  # Replace with your location.

# Request the forecast from the API.
# Keep the key on your server or local machine, never in frontend code.
response = requests.get(
    f"https://api.rainbow.ai/nowcast/v1/precip-global/{LON}/{LAT}",
    headers={"Ocp-Apim-Subscription-Key": os.environ["RAINBOW_API_KEY"]},
    timeout=15,
)
response.raise_for_status()

# Prepare the intensity data.
forecast = sorted(
    response.json()["forecast"],
    key=lambda row: row["timestampBegin"],
)
if not forecast:
    raise ValueError("No forecast available for this location.")
if any(row["timestampEnd"] - row["timestampBegin"] != 60 for row in forecast):
    raise ValueError("Expected one-minute forecast intervals.")

start, end = forecast[0]["timestampBegin"], forecast[-1]["timestampEnd"]
rates = np.full((end - start) // 60, np.nan)  # Missing minutes remain blank.
for row in forecast:
    rates[(row["timestampBegin"] - start) // 60] = row["precipRate"]

left, right = [
    mdates.date2num(datetime.fromtimestamp(t, timezone.utc))
    for t in (start, end)
]

# Draw the chart.
plt.style.use("seaborn-v0_8-whitegrid")
fig, ax = plt.subplots(figsize=(10, 2.5), dpi=160, layout="constrained")
strip = ax.imshow(
    [rates],
    extent=(left, right, 0, 1),
    aspect="auto",
    interpolation="nearest",
    cmap="Blues",
    vmin=0,
    vmax=max(0.1, np.nanmax(rates)),
)
ax.set(title="Precipitation intensity", xlabel="Time (UTC)", yticks=[])
ax.grid(False)
ax.xaxis.set_major_locator(
    mdates.AutoDateLocator(minticks=3, maxticks=5, tz=timezone.utc)
)
ax.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M", tz=timezone.utc))
fig.colorbar(
    strip,
    ax=ax,
    orientation="horizontal",
    label="Precipitation rate (mm/h)",
)

# Save and display the chart.
fig.savefig(
    "nowcast-intensity-strip.jpg",
    pil_kwargs={"quality": 94, "optimize": True},
)
plt.show()

Run:

Bash
python intensity_strip.py

Displays the chart and saves nowcast-intensity-strip.jpg.

All charts use UTC and the API's original values. Precipitation rate is measured in mm/h, not the amount accumulated in one minute.

The forecast will differ when you run a script. For a browser app, fetch the forecast through your backend and keep the key on the server.