Skip to content

Wind rose

Plot the direction and speed of the next 48 hours of wind with Python and Matplotlib.

Weather Forecast API · API reference

Keep your API key on the server

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

Wind rose with 16 direction sectors and colors representing wind speed

  • Direction: hourly forecasts are grouped into 16 compass sectors, with north at the top and directions increasing clockwise.
  • Color: the built-in Blues colormap goes from light to dark across five speed ranges in m/s — 0–3, 3–6, 6–9, 9–12, and ≥12. Lower bounds are inclusive and upper bounds are exclusive.
  • Size: the radial scale shows the percentage of valid forecast hours in each direction.
  • Calm: wind below 0.5 m/s is shown separately. Direction sectors and calm share the same total and sum to 100%.

Missing or invalid speeds are excluded. Non-calm readings also need a valid direction.

One line selects Matplotlib's built-in seaborn-v0_8-whitegrid theme, and layout="constrained" arranges the chart automatically. Use Matplotlib 3.6 or later; no separate Seaborn installation is needed.

Python example

Save as wind_rose.py and replace LON, LAT, and LOCATION with your location.

wind_rose.py
import os

import matplotlib.pyplot as plt
from matplotlib.ticker import PercentFormatter
import numpy as np
import requests

plt.style.use("seaborn-v0_8-whitegrid")

LON, LAT = -0.1278, 51.5074
LOCATION = "London"

# 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/weather/v1/forecast/{LON}/{LAT}",
    params={"forecast_hours": 48},
    headers={"Ocp-Apim-Subscription-Key": os.environ["RAINBOW_API_KEY"]},
    timeout=30,
)
response.raise_for_status()
data = response.json()

# Prepare the wind data.
if (
    data["units"]["windSpeed"] != "meter_per_second"
    or data["units"]["windDirection"] != "degree"
):
    raise ValueError("This example expects wind speed in m/s and direction in degrees.")

hourly = data["timelines"]["hourly"]
speeds = np.array(
    [hour.get("windSpeed", np.nan) for hour in hourly],
    dtype=float,
)
directions = np.array(
    [hour.get("windDirection", np.nan) for hour in hourly],
    dtype=float,
)

calm = (speeds >= 0) & (speeds < 0.5)
moving = (
    np.isfinite(speeds)
    & (speeds >= 0.5)
    & (directions >= 0)
    & (directions <= 360)
)
valid_hours = np.count_nonzero(calm | moving)

if valid_hours == 0:
    raise ValueError("No valid hourly wind forecasts are available.")

sector_counts, _, _ = np.histogram2d(
    (directions[moving] + 11.25) % 360,
    speeds[moving],
    bins=[np.linspace(0, 360, 17), [0, 3, 6, 9, 12, np.inf]],
)
sector_percent = sector_counts / valid_hours * 100
calm_percent = np.count_nonzero(calm) / valid_hours * 100

# Draw the chart.
fig, ax = plt.subplots(
    figsize=(10, 6),
    dpi=160,
    layout="constrained",
    subplot_kw={"projection": "polar"},
)
angles = np.linspace(0, 2 * np.pi, 16, endpoint=False)
speed_labels = ["0–3", "3–6", "6–9", "9–12", "≥12"]
colors = plt.cm.Blues(np.linspace(0.3, 0.9, 5))
bottom = np.zeros(16)

for index, (label, color) in enumerate(zip(speed_labels, colors)):
    ax.bar(
        angles,
        sector_percent[:, index],
        width=np.pi / 8,
        bottom=bottom,
        color=color,
        label=label,
    )
    bottom += sector_percent[:, index]

ax.set_theta_zero_location("N")
ax.set_theta_direction(-1)
ax.set_xticks(angles[::2], ["N", "NE", "E", "SE", "S", "SW", "W", "NW"])
ax.set_ylim(0, max(5, bottom.max() * 1.1))
ax.yaxis.set_major_formatter(PercentFormatter(xmax=100))
ax.set_title(f"{LOCATION} · 48-hour wind forecast\nCalm (<0.5 m/s): {calm_percent:.1f}%")
ax.legend(title="Wind speed (m/s)", loc="upper left", bbox_to_anchor=(1.1, 1))

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

Run locally

Install the dependencies and set your key from Getting started:

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

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

The script displays the chart and saves wind-rose.jpg in the current folder. It checks that the response uses meters per second for speed and degrees for direction.