svgbrushablebar
Bar chart
How often does each category occur?
How to read it
- Compare bar lengths: they all start at zero, so length is the value.
- Read from the longest down for the ranking.
- Check whether an “Other” bar groups levels beyond the top ones.
- Callout 1: Bar length: the count or share.
- Callout 2: The small categories together may still matter.
Watch out
- Never cut the y axis on a bar chart: bars encode length, so a truncated axis exaggerates differences.
Defaults
- Value
- Count
- Show counts or shares.
- Also: Percent
- Orientation
- Columns
- Draw bars vertically or horizontally; horizontal suits long labels.
- Also: Bars
- Order
- By frequency
- How rows or groups are ordered.
- Also: Alphabetical
- Top levels
- 12
- How many levels to show; the rest are grouped into Other.
- Range 3 to 30, step 1
- Colour
- Single
- How bars or lines are coloured.
- Also: By level
- Value labels
- On
- Print each value on the chart.
Pinned in the code
- Levels sorted by descending count (ties alphabetical) unless an order is declared in the data dictionary.
- Levels beyond the top k are pooled into “Other” (drawn in neutral grey); missing values are excluded and reported separately.
- Percent = count / non-missing rows.
# Bar chart — Codesplash Chart Lab (recipe "bar")
# controls: value=count, orientation=vertical, order=freq, top=12, color=single, 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-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
counts = df["channel"].dropna().astype(str).value_counts() # missing values excluded
counts = counts.sort_values(ascending=False, kind="stable") # by frequency
if len(counts) > 12: # pool levels beyond the top 12 into "Other"
top = counts.sort_values(ascending=False).iloc[:12]
counts = pd.concat([counts[counts.index.isin(top.index)], pd.Series({"Other": counts.drop(top.index).sum()})])
values = counts
colors = [PALETTE[0] if k != "Other" else "#9aa0a6" for k in values.index]
fig, ax = plt.subplots(figsize=(7, 4))
bars = ax.bar(values.index, values.values, color=colors)
ax.bar_label(bars, fmt="%d", padding=2, fontsize=8)
ax.set_ylabel("Count")
ax.tick_params(axis="x", labelrotation=30)
ax.set_xlabel("channel")
plt.show()Needs pandas, numpy, matplotlib · reads bar-demo.csv · app theme from the optional codesplash helper
# Bar chart — Codesplash Chart Lab (recipe "bar")
# controls: value=count, orientation=vertical, order=freq, top=12, color=single, 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-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
counts = df["channel"].dropna().astype(str).value_counts()
counts = counts.sort_values(ascending=False, kind="stable")
if len(counts) > 12:
top = counts.sort_values(ascending=False).iloc[:12]
counts = pd.concat([counts[counts.index.isin(top.index)], pd.Series({"Other": counts.drop(top.index).sum()})])
values = counts
frame = pd.DataFrame({"level": values.index, "value": values.values})
fig = px.bar(frame, x="level", y="value", text_auto="d")
fig.update_layout(showlegend=False, yaxis_title="Count", xaxis_title="channel")
fig.show()Needs pandas, numpy, plotly · reads bar-demo.csv · app theme from the optional codesplash helper
# Bar chart — Codesplash Chart Lab (recipe "bar")
# controls: value=count, orientation=vertical, order=freq, top=12, color=single, 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-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["channel"]] <- factor(df[["channel"]])
v <- as.character(df[["channel"]])
v <- v[!is.na(v)] # missing values excluded
counts <- sort(table(v), decreasing = TRUE)
if (length(counts) > 12) { # pool levels beyond the top 12 into "Other"
counts <- c(counts[seq_len(12)], Other = sum(counts[-seq_len(12)]))
}
bars <- data.frame(level = names(counts), n = as.numeric(counts))
bars$value <- bars$n
bars$level <- factor(bars$level, levels = bars$level) # by frequency
fill <- setNames(rep(cs_cat[1], nlevels(bars$level)), levels(bars$level))
if ("Other" %in% names(fill)) fill[["Other"]] <- "#9aa0a6" # pooled levels in neutral grey
p <- ggplot(bars, aes(x = level, y = value, fill = level)) +
geom_col(show.legend = FALSE) +
scale_fill_manual(values = fill) +
geom_text(aes(label = value), vjust = -0.4, size = 3) +
labs(x = "channel", y = "Count") +
theme_cs
print(p)Needs ggplot2 · reads bar-demo.csv · app theme from the optional codesplashr helper
-- Bar chart — Codesplash Chart Lab (recipe "bar")
-- controls: value=count, orientation=vertical, order=freq, top=12, color=single, labels=true
-- counts per level, top 12 kept and the rest pooled into 'Other'; missing excluded
WITH counts AS (
SELECT "channel"::VARCHAR AS level, count(*) AS n
FROM read_csv('bar-demo.csv')
WHERE "channel" IS NOT NULL
GROUP BY ALL
),
ranked AS (SELECT *, row_number() OVER (ORDER BY n DESC, level) AS rk FROM counts)
SELECT CASE WHEN rk <= 12 THEN level ELSE 'Other' END AS level,
sum(n) AS count,
sum(n) / (SELECT sum(n) FROM counts) AS share
FROM ranked
GROUP BY ALL
ORDER BY min(rk);Needs duckdb · reads bar-demo.csv