svgpie
Pie / donut
What share of the whole does each of a few categories hold?
How to read it
- Read the slices as shares of a whole.
- Compare with 25% and 50%: those angles are the easiest to judge.
- Use the legend for exact percentages.
- Callout 1: Largest first, starting at twelve o'clock.
- Callout 2: The centre shows the total.
- Callout 3: Legend: the exact share per slice.
Watch out
- People compare angles poorly: with more than a few slices, a bar chart is clearer.
Defaults
- Donut
- On
- Cut a hole in the middle, with the total shown there.
- Percent labels (≥ 6 %)
- On
- Print the share on slices large enough to hold a label.
- Slices (incl. Other)
- 6
- How many slices to draw, with Other as the last.
- Range 2 to 8, step 1
Pinned in the code
- Share = value / total over non-missing categories; slices sorted by value, clockwise from 12 o'clock.
- At most 6 slices: the top 5 levels plus “Other” (grey) when there are more.
- Percent labels are drawn on slices of at least 6 %; every share is in the legend.
Use with care
Consider a bar chart: angles are harder to compare than lengths.
# Pie / donut — Codesplash Chart Lab (recipe "pie")
# controls: donut=true, labels=true, top=6
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
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("pie-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
OTHER = "#9aa0a6" # pooled levels
d = df[df["browser"].notna()].copy()
d["_k"] = d["browser"].astype(str)
d["_v"] = 1.0 # no value column: count rows
sums = d.groupby("_k", sort=False)["_v"].sum() # first-appearance order
if isinstance(df["browser"].dtype, pd.CategoricalDtype): # declared order first
declared = [str(l) for l in df["browser"].cat.categories]
sums = sums.reindex([l for l in declared if l in sums.index] + [s for s in sums.index if s not in declared])
s = sums[sums > 0].rename("value").rename_axis("label").reset_index()
s = s.sort_values(["value", "label"], ascending=[False, True]) # largest first, ties alphabetical
if len(s) > 6: # top 6 − 1 levels plus "Other"
s = pd.concat([s.iloc[: 6 - 1], pd.DataFrame({"label": ["Other"], "value": [s["value"].iloc[6 - 1:].sum()]})], ignore_index=True)
s["share"] = s["value"] / s["value"].sum()
colors = [OTHER if l == "Other" else PALETTE[i % len(PALETTE)] for i, l in enumerate(s["label"])]
fig, ax = plt.subplots(figsize=(7, 4.5))
wedges, *_ = ax.pie(
s["value"], colors=colors, startangle=90, counterclock=False, # clockwise from 12 o'clock
wedgeprops=dict(width=0.42, edgecolor=plt.rcParams["axes.facecolor"], linewidth=1),
autopct=lambda p: f"{p:.0f}%" if p >= 6 else "", pctdistance=0.79, textprops=dict(fontsize=8, color="white"), # labels on slices ≥ 6 %
)
ax.legend(wedges, [f"{l} {sh:.1%}" for l, sh in zip(s["label"], s["share"])], loc="center left", bbox_to_anchor=(1.0, 0.5))
ax.set_aspect("equal")
plt.show()Needs pandas, numpy, matplotlib · reads pie-demo.csv · app theme from the optional codesplash helper
# Pie / donut — Codesplash Chart Lab (recipe "pie")
# controls: donut=true, labels=true, top=6
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
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("pie-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
OTHER = "#9aa0a6" # pooled levels
d = df[df["browser"].notna()].copy()
d["_k"] = d["browser"].astype(str)
d["_v"] = 1.0 # no value column: count rows
sums = d.groupby("_k", sort=False)["_v"].sum() # first-appearance order
if isinstance(df["browser"].dtype, pd.CategoricalDtype): # declared order first
declared = [str(l) for l in df["browser"].cat.categories]
sums = sums.reindex([l for l in declared if l in sums.index] + [s for s in sums.index if s not in declared])
s = sums[sums > 0].rename("value").rename_axis("label").reset_index()
s = s.sort_values(["value", "label"], ascending=[False, True]) # largest first, ties alphabetical
if len(s) > 6: # top 6 − 1 levels plus "Other"
s = pd.concat([s.iloc[: 6 - 1], pd.DataFrame({"label": ["Other"], "value": [s["value"].iloc[6 - 1:].sum()]})], ignore_index=True)
s["share"] = s["value"] / s["value"].sum()
colors = [OTHER if l == "Other" else PALETTE[i % len(PALETTE)] for i, l in enumerate(s["label"])]
fig = go.Figure(go.Pie(labels=s["label"], values=s["value"], sort=False, direction="clockwise", rotation=0, # from 12 o'clock
hole=0.58, marker=dict(colors=colors),
text=[f"{p:.0%}" if p >= 0.06 else "" for p in s["share"]], textinfo="text"))
fig.show()Needs pandas, numpy, plotly · reads pie-demo.csv · app theme from the optional codesplash helper
# Pie / donut — Codesplash Chart Lab (recipe "pie")
# controls: donut=true, labels=true, top=6
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("pie-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["browser"]] <- factor(df[["browser"]])
update_geom_defaults("text", list(colour = "#131922")) # labels in the theme's text colour
k <- as.character(df[["browser"]])
v <- rep(1, length(k)) # no value column: count rows
v[!is.finite(v)] <- 0
ok <- !is.na(k)
ord <- unique(k[ok]) # first appearance
sums <- tapply(v[ok], k[ok], sum)[ord]
s <- data.frame(label = names(sums), value = as.numeric(sums))
s <- s[s$value > 0, ]
s <- s[order(-s$value, s$label), ] # largest first, ties alphabetical
if (nrow(s) > 6) s <- rbind(head(s, 6 - 1), data.frame(label = "Other", value = sum(s$value[-seq_len(6 - 1)])))
s$share <- s$value / sum(s$value)
s$end <- cumsum(s$share)
s$start <- s$end - s$share
fill <- setNames(rep(cs_cat, length.out = nrow(s)), s$label)
fill[s$label == "Other"] <- "#9aa0a6"
legend <- sprintf("%s %.1f%%", s$label, 100 * s$share)
p <- ggplot(s) +
geom_rect(aes(xmin = 0.58, xmax = 1, ymin = start, ymax = end, fill = label), colour = "white", linewidth = 0.4) +
geom_text(aes(x = 0.79, y = (start + end) / 2, label = ifelse(share >= 0.06, sprintf("%.0f%%", 100 * share), "")), colour = "white", size = 2.8) + # labels on slices ≥ 6 %
scale_fill_manual(values = fill, breaks = s$label, labels = legend, name = NULL) +
scale_x_continuous(limits = c(0, 1)) +
coord_polar(theta = "y", start = 0, direction = 1) + # clockwise from 12 o'clock
theme_cs +
theme(axis.text = element_blank(), axis.title = element_blank(), axis.ticks = element_blank(), axis.line = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank())
print(p)Needs ggplot2 · reads pie-demo.csv · app theme from the optional codesplashr helper
-- Pie / donut — Codesplash Chart Lab (recipe "pie")
-- controls: donut=true, labels=true, top=6
-- shares per category: top 5 by value plus 'Other' (when there are more than 6)
WITH sums AS (
SELECT "browser"::VARCHAR AS label, count(*) AS value
FROM read_csv('pie-demo.csv') WHERE "browser" IS NOT NULL
GROUP BY 1 HAVING value > 0
),
ranked AS (SELECT *, row_number() OVER (ORDER BY value DESC, label) AS rk, count(*) OVER () AS k FROM sums),
pooled AS (
SELECT CASE WHEN k <= 6 OR rk < 6 THEN label ELSE 'Other' END AS label, sum(value) AS value, min(rk) AS rk
FROM ranked GROUP BY 1
)
SELECT label, value, value / sum(value) OVER () AS share
FROM pooled
ORDER BY rk;Needs duckdb · reads pie-demo.csv