svgbrushablebar-ranked
Ranked bars
Which categories lead on a total, mean or median?
How to read it
- Read top down: categories are ranked by the aggregate.
- Check the labels for the exact values.
- Check which aggregate is shown: a total favours big categories, a mean does not.
- Callout 1: The leader on this aggregate.
- Callout 2: The value label on each bar.
Watch out
- A top-N view hides the rest: say how much the omitted categories add up to.
Defaults
- Aggregate
- Sum
- How rows combine into one number per group or period, such as a sum or a mean.
- Also: Mean · Median · Count
- Top N
- 12
- How many categories to show.
- Range 3 to 30, step 1
- Order
- Largest first
- How rows or groups are ordered.
- Also: Smallest first
- Value labels
- On
- Print each value on the chart.
Pinned in the code
- Aggregates per category: sum, mean, median (type-7 quantile) or row count; rows with a missing category or value are dropped.
- Ranked by the aggregate (ties alphabetical) and cut to the top N — the rest are not pooled, so the axis is not a share of a total.
- Bars start at zero; for means and medians a selection shows the selected rows' aggregate as a marker, for sums and counts as an inner bar.
# Ranked bars — Codesplash Chart Lab (recipe "bar-ranked")
# controls: stat=sum, top=12, order=desc, labels=true
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("bar-ranked-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
d = df[["product", "revenue"]].dropna() # rows with a missing category or value dropped
agg = d.groupby(d["product"].astype(str))["revenue"].agg("sum").rename("value").reset_index()
agg = agg[np.isfinite(agg["value"].astype(float))]
agg = agg.sort_values(["value", "product"], ascending=[False, True]).head(12) # ties alphabetical
fig, ax = plt.subplots(figsize=(7, 4.5))
y = np.arange(len(agg))[::-1] # first ranked on top
bars = ax.barh(y, agg["value"], color=PALETTE[0], height=0.7)
for yi, v in zip(y, agg["value"]):
ax.annotate(f"{v:,.0f}" if abs(v) >= 100 else f"{v:.3g}", (v, yi), xytext=(3, 0), textcoords="offset points", va="center", fontsize=8)
ax.axvline(0, color=plt.rcParams["axes.edgecolor"], linewidth=0.8) # bars/stems start at zero
ax.set_yticks(y, agg["product"])
ax.set_xlabel("Sum of revenue")
ax.set_ylabel("product")
plt.show()Needs pandas, numpy, matplotlib · reads bar-ranked-demo.csv · app theme from the optional codesplash helper
# Ranked bars — Codesplash Chart Lab (recipe "bar-ranked")
# controls: stat=sum, top=12, order=desc, labels=true
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("bar-ranked-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
d = df[["product", "revenue"]].dropna() # rows with a missing category or value dropped
agg = d.groupby(d["product"].astype(str))["revenue"].agg("sum").rename("value").reset_index()
agg = agg[np.isfinite(agg["value"].astype(float))]
agg = agg.sort_values(["value", "product"], ascending=[False, True]).head(12) # ties alphabetical
fig = px.bar(agg, x="value", y="product", orientation="h", color_discrete_sequence=[PALETTE[0]], text_auto=",.0f")
fig.update_layout(xaxis_title="Sum of revenue", yaxis_title="product", yaxis_autorange="reversed", xaxis_rangemode="tozero")
fig.show()Needs pandas, numpy, plotly · reads bar-ranked-demo.csv · app theme from the optional codesplash helper
# Ranked bars — Codesplash Chart Lab (recipe "bar-ranked")
# controls: stat=sum, top=12, order=desc, labels=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("bar-ranked-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["product"]] <- factor(df[["product"]])
update_geom_defaults("text", list(colour = "#131922")) # labels in the theme's text colour
cat <- as.character(df[["product"]])
val <- df[["revenue"]]
ok <- !is.na(cat) & !is.na(val)
agg <- tapply(val[ok], cat[ok], sum)
r <- data.frame(level = names(agg), value = as.numeric(agg))
r <- r[is.finite(r$value), ]
r <- head(r[order(-r$value, r$level), ], 12) # ties alphabetical
r$level <- factor(r$level, levels = rev(r$level)) # first ranked on top
p <- ggplot(r, aes(value, level)) +
geom_col(fill = cs_cat[1], width = 0.7) +
geom_text(aes(label = prettyNum(signif(value, 4), big.mark = ",")), hjust = -0.1, size = 2.8) +
geom_vline(xintercept = 0, linewidth = 0.3) +
scale_x_continuous(expand = expansion(mult = c(0, 0.12))) +
labs(x = "Sum of revenue", y = "product") +
theme_cs
print(p)Needs ggplot2 · reads bar-ranked-demo.csv · app theme from the optional codesplashr helper
-- Ranked bars — Codesplash Chart Lab (recipe "bar-ranked")
-- controls: stat=sum, top=12, order=desc, labels=true
-- Sum of revenue per category, ranked (ties alphabetical), top 12
SELECT "product"::VARCHAR AS level, sum("revenue") AS value, count(*) AS n
FROM read_csv('bar-ranked-demo.csv')
WHERE "product" IS NOT NULL AND "revenue" IS NOT NULL
GROUP BY 1
ORDER BY value DESC, level
LIMIT 12;Needs duckdb · reads bar-ranked-demo.csv