svgwind-rose
Wind rose
From which directions does it come, and how strong is it from each?
How to read it
- Read each spoke's length as the share of observations from that direction.
- Read colours as magnitude classes.
- Longer dark spokes mean frequent and strong.
- Callout 1: The dominant direction.
- Callout 2: A spoke of strong values.
- Callout 3: Magnitude classes.
Watch out
- Direction is where it comes from in meteorology: check the units setting.
Defaults
- Angles are in
- Degrees
- How the column measures direction; the dial is labelled to match.
- Also: Radians · Hours of the day · Weekday (1 = Mon) · Month (1–12) · Day of year
- Zero and direction
- Top, clockwise (compass, clock)
- Compass bearings and clock times start at the top and run clockwise; mathematical angles start at the right.
- Also: Right, counter-clockwise (maths)
- Sectors
- 16
- How many sectors divide the circle.
- Range 4 to 36, step 4
- Magnitude classes
- 5
- How many strength classes to colour.
- Range 2 to 8, step 1
- Show percentages
- On
- Label the rings with percentages.
Pinned in the code
- Sectors are centred on the compass points (N covers 348.75°–11.25° with 16 sectors); length ∝ count (linear, the meteorological convention).
- Magnitude classes have equal, rounded widths from 0 to the maximum; the last class is open-ended.
# Wind rose — Codesplash Chart Lab (recipe "wind-rose")
# controls: units=degrees, orientation=compass, bins=16, classes=5, percent=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else plt.rcParams["axes.prop_cycle"].by_key()["color"]
df = pd.read_csv("wind-rose-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"]) # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"]) # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
UNITS, COMPASS = "degrees", True # compass: 0 at the top, clockwise; else 0 at the right, counter-clockwise
PERIOD, ORIGIN = 360, 0 # one full turn, and the value at angle 0
TICK_T = [0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875]
TICK_LABELS = ["0°", "45°", "90°", "135°", "180°", "225°", "270°", "315°"]
def to_turn(v):
return np.mod((np.asarray(v, dtype=float) - ORIGIN) / PERIOD, 1.0)
def dial(ax):
ax.set_theta_zero_location("N" if COMPASS else "E")
ax.set_theta_direction(-1 if COMPASS else 1)
ax.set_xticks([2 * np.pi * t for t in TICK_T], TICK_LABELS)
ax.grid(True, linewidth=0.5, alpha=0.6)
def speed_breaks(s, classes):
"""Breaks from 0 in rounded steps (1, 2, 2.5, 5, 10 × 10^k) covering the maximum."""
mx = float(np.nanmax(s)) if len(s) else 0.0
if not mx > 0:
return np.array([0.0, 1.0])
raw = mx / classes
mag = 10 ** np.floor(np.log10(raw))
step = next((m * mag for m in (1, 2, 2.5, 5, 10) if m * mag >= raw), raw)
return np.round(np.arange(classes + 1) * step, 6)
def class_of(v, breaks):
"""Class index (last class open-ended)."""
return np.clip(np.searchsorted(breaks[:-1], v, side="right") - 1, 0, len(breaks) - 2)
A = "direction"
MAG = "speed"
BINS, CLASSES, PERCENT = 16, 5, True
d = df.dropna(subset=[A, MAG])
t, s = to_turn(d[A]), d[MAG].to_numpy(float)
breaks = speed_breaks(s, CLASSES)
K = len(breaks) - 1
cls = class_of(s, breaks)
b = np.minimum(BINS - 1, np.floor(((t + 0.5 / BINS) % 1) * BINS).astype(int)) # sectors centred on the compass points
counts = np.zeros((K, BINS))
np.add.at(counts, (cls, b), 1)
n, top = len(t), counts.sum(axis=0).max() or 1
cmap = LinearSegmentedColormap.from_list("seq", SEQ)
fig, ax = plt.subplots(figsize=(6.6, 6.6), subplot_kw={"projection": "polar"})
dial(ax)
start = 2 * np.pi * (np.arange(BINS) - 0.5) / BINS
acc = np.zeros(BINS)
for k in range(K): # magnitude classes stack outward; length = share of observations
label = f"{breaks[k]:g}–{breaks[k + 1]:g}" if k < K - 1 else f"≥ {breaks[k]:g}"
ax.bar(start, counts[k] / top, bottom=acc / top, width=0.92 * 2 * np.pi / BINS, align="edge", color=cmap(0.18 + 0.82 * k / max(1, K - 1)),
edgecolor="white", linewidth=0.5, label=label)
acc += counts[k]
fr = [0.25, 0.5, 0.75, 1]
ax.set_ylim(0, 1)
ax.set_yticks(fr, [f"{100 * round(top * f) / n:.1f}%" if PERCENT else str(round(top * f)) for f in fr], fontsize=8)
ax.legend(title=MAG, fontsize=8, loc="upper right", bbox_to_anchor=(1.22, 1.1))
plt.show()Needs pandas, numpy, matplotlib · reads wind-rose-demo.csv · app theme from the optional codesplash helper
# Wind rose — Codesplash Chart Lab (recipe "wind-rose")
# controls: units=degrees, orientation=compass, bins=16, classes=5, percent=true
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.colors import sample_colorscale
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("wind-rose-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"]) # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"]) # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
UNITS, COMPASS = "degrees", True # compass: 0 at the top, clockwise; else 0 at the right, counter-clockwise
PERIOD, ORIGIN = 360, 0 # one full turn, and the value at angle 0
TICK_T = [0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875]
TICK_LABELS = ["0°", "45°", "90°", "135°", "180°", "225°", "270°", "315°"]
def to_turn(v):
return np.mod((np.asarray(v, dtype=float) - ORIGIN) / PERIOD, 1.0)
POLAR = dict(angularaxis=dict(rotation=90 if COMPASS else 0, direction="clockwise" if COMPASS else "counterclockwise",
tickmode="array", tickvals=[360 * t for t in TICK_T], ticktext=TICK_LABELS))
def speed_breaks(s, classes):
"""Breaks from 0 in rounded steps (1, 2, 2.5, 5, 10 × 10^k) covering the maximum."""
mx = float(np.nanmax(s)) if len(s) else 0.0
if not mx > 0:
return np.array([0.0, 1.0])
raw = mx / classes
mag = 10 ** np.floor(np.log10(raw))
step = next((m * mag for m in (1, 2, 2.5, 5, 10) if m * mag >= raw), raw)
return np.round(np.arange(classes + 1) * step, 6)
def class_of(v, breaks):
"""Class index (last class open-ended)."""
return np.clip(np.searchsorted(breaks[:-1], v, side="right") - 1, 0, len(breaks) - 2)
A = "direction"
MAG = "speed"
BINS, CLASSES, PERCENT = 16, 5, True
d = df.dropna(subset=[A, MAG])
t, s = to_turn(d[A]), d[MAG].to_numpy(float)
breaks = speed_breaks(s, CLASSES)
K = len(breaks) - 1
b = np.minimum(BINS - 1, np.floor(((t + 0.5 / BINS) % 1) * BINS).astype(int))
counts = np.zeros((K, BINS))
np.add.at(counts, (class_of(s, breaks), b), 1)
n, top = len(t), counts.sum(axis=0).max() or 1
colours = sample_colorscale([[i / (len(SEQ) - 1), col] for i, col in enumerate(SEQ)], [0.18 + 0.82 * k / max(1, K - 1) for k in range(K)])
fig = go.Figure()
acc = np.zeros(BINS)
for k in range(K):
label = f"{breaks[k]:g}–{breaks[k + 1]:g}" if k < K - 1 else f"≥ {breaks[k]:g}"
fig.add_barpolar(r=counts[k] / top, base=acc / top, theta=360 * np.arange(BINS) / BINS, width=0.92 * 360 / BINS, name=label,
marker=dict(color=colours[k], line=dict(color="white", width=0.5)))
acc += counts[k]
fr = [0.25, 0.5, 0.75, 1]
fig.update_layout(polar=dict(**POLAR, radialaxis=dict(range=[0, 1], tickvals=fr, ticktext=[f"{100 * round(top * f) / n:.1f}%" if PERCENT else str(round(top * f)) for f in fr])),
legend_title_text=MAG)
fig.show()Needs pandas, numpy, plotly · reads wind-rose-demo.csv · app theme from the optional codesplash helper
# Wind rose — Codesplash Chart Lab (recipe "wind-rose")
# controls: units=degrees, orientation=compass, bins=16, classes=5, percent=true
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("wind-rose-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
compass <- TRUE # compass: 0 at the top, clockwise; else 0 at the right, counter-clockwise
period <- 360; origin <- 0 # one full turn, and the value at angle 0 (degrees)
tick_t <- c(0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875)
tick_labels <- c("0°", "45°", "90°", "135°", "180°", "225°", "270°", "315°")
to_turn <- function(v) ((v - origin) / period) %% 1
dial <- list(coord_polar(start = if (compass) 0 else -pi / 2, direction = if (compass) 1 else -1),
scale_x_continuous(limits = c(0, 1), breaks = tick_t, labels = tick_labels, expand = c(0, 0)))
a_col <- "direction"
mag_col <- "speed"
bins <- 16; classes <- 5; percent <- TRUE
d <- df[!is.na(df[[a_col]]) & !is.na(df[[mag_col]]), ]
t <- to_turn(d[[a_col]]); s <- d[[mag_col]]; n <- length(t)
mx <- max(s, 0) # breaks from 0 in rounded steps (1, 2, 2.5, 5, 10 x 10^k)
breaks <- if (mx > 0) { raw <- mx / classes; mag <- 10^floor(log10(raw)); st <- c(1, 2, 2.5, 5, 10) * mag; round(seq(0, classes) * (if (any(st >= raw)) st[st >= raw][1] else raw), 6) } else c(0, 1)
K <- length(breaks) - 1
cls <- pmax(1, findInterval(s, breaks[seq_len(K)])) # last class open-ended
b <- pmin(bins - 1, floor(((t + 0.5 / bins) %% 1) * bins)) # sectors centred on the compass points
counts <- table(factor(cls, levels = seq_len(K)), factor(b, levels = 0:(bins - 1)))
top <- max(colSums(counts), 1)
fmt_b <- function(v) format(v, trim = TRUE, drop0trailing = TRUE)
labels <- ifelse(seq_len(K) < K, paste0(fmt_b(breaks[seq_len(K)]), "–", fmt_b(breaks[seq_len(K) + 1])), paste0("≥ ", fmt_b(breaks[K])))
cols <- grDevices::colorRampPalette(seq_ramp)(101)[round(100 * (0.18 + 0.82 * (seq_len(K) - 1) / max(1, K - 1))) + 1]
bars <- do.call(rbind, lapply(0:(bins - 1), function(j) { cum <- cumsum(counts[, j + 1])
data.frame(k = factor(labels, levels = labels), x0 = ((j - 0.5) / bins) %% 1, r0 = c(0, head(cum, -1)) / top, r1 = cum / top) }))
bars$x1 <- bars$x0 + 0.92 / bins
wrap <- bars$x1 > 1 # the north sector straddles 0: draw its two parts
bars <- rbind(transform(bars, x1 = pmin(x1, 1)), transform(bars[wrap, ], x0 = 0, x1 = x1 - 1))
fr <- c(0.25, 0.5, 0.75, 1)
p <- ggplot(bars) + geom_rect(aes(xmin = x0, xmax = x1, ymin = r0, ymax = r1, fill = k), colour = "white", linewidth = 0.2) +
dial + scale_y_continuous(limits = c(0, 1), breaks = fr, labels = if (percent) sprintf("%.1f%%", 100 * round(top * fr) / n) else round(top * fr)) +
scale_fill_manual(values = stats::setNames(cols, labels)) + labs(x = NULL, y = NULL, fill = mag_col) + theme_cs
print(p)Needs ggplot2 · reads wind-rose-demo.csv · app theme from the optional codesplashr helper