svglikert
Likert diverging bars
How do agreement levels compare across survey items?
How to read it
- The centre of the chart is neutral: disagreement grows to the left, agreement to the right.
- Compare how far each bar reaches on each side.
- Read the order: items are ranked by net agreement.
- Callout 1: Centre: the neutral responses straddle zero.
- Callout 2: Right side: the share who agree.
- Callout 3: Left side: the share who disagree.
Watch out
- Response categories are ordered but not evenly spaced, so a mean of codes can mislead.
- Check the sample size per item before ranking small differences.
Defaults
- Order
- By net agreement
- How rows or groups are ordered.
- Also: As listed
- Percent labels
- On
- Print each segment's share.
Pinned in the code
- Shares are per item over its non-missing responses; response order comes from the dictionary's ordinal levels (default 5-point Strongly disagree … Strongly agree).
- With an odd number of levels the middle level is neutral and is split half left, half right of zero, so bars centre on neutral (Robbins & Heiberger 2011).
- Net agreement = agree shares − disagree shares (neutral excluded); items are ranked by it.
- A selection adds a thin outlined bar under each item with the selected respondents' shares.
# Likert diverging bars — Codesplash Chart Lab (recipe "likert")
# controls: sort=net, 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("likert-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["Meaningful work"] = pd.Categorical(df["Meaningful work"].astype("string"), categories=["Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"])
df["Clear goals"] = pd.Categorical(df["Clear goals"].astype("string"), categories=["Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"])
df["Manager support"] = pd.Categorical(df["Manager support"].astype("string"), categories=["Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"])
df["Fair pay"] = pd.Categorical(df["Fair pay"].astype("string"), categories=["Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"])
df["Work–life balance"] = pd.Categorical(df["Work–life balance"].astype("string"), categories=["Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"])
df["Growth opportunities"] = pd.Categorical(df["Growth opportunities"].astype("string"), categories=["Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"])
ITEMS = ["Meaningful work", "Clear goals", "Manager support", "Fair pay", "Work–life balance", "Growth opportunities"]
LEVELS = ["Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"] # response order from the data dictionary
COLORS = ["#c95443", "#da8477", "#ced1d6", "#6691ca", "#2a69b5"] # disagree … neutral … agree
k = len(LEVELS)
mid = (k - 1) / 2 # with an odd number of levels the middle one is neutral
shares = {}
for item in ITEMS:
s = df[item].dropna().astype(str)
s = s[s.isin(LEVELS)]
shares[item] = s.value_counts().reindex(LEVELS, fill_value=0) / max(len(s), 1) # share of non-missing responses
shares = pd.DataFrame(shares).T * 100 # items × levels, percent
neg = shares[[l for j, l in enumerate(LEVELS) if j < mid]].sum(axis=1)
pos = shares[[l for j, l in enumerate(LEVELS) if j > mid]].sum(axis=1)
neutral = shares[[l for j, l in enumerate(LEVELS) if j == mid]].sum(axis=1)
net = pos - neg # net agreement
start = -(neg + neutral / 2) # half the neutral share on each side of zero
order = list(net.sort_values(ascending=False, kind="stable").index) # by net agreement
fig, ax = plt.subplots(figsize=(8, 4.5))
y = np.arange(len(order))[::-1] # first item on top
for yi, item in zip(y, order):
left = start[item]
for j, lvl in enumerate(LEVELS):
w = shares.loc[item, lvl]
ax.barh(yi, w, left=left, color=COLORS[j], height=0.7, label=lvl if yi == y[0] else None)
if w >= 6:
ax.text(left + w / 2, yi, f"{w:.0f}", ha="center", va="center", fontsize=7)
left += w
ax.axvline(0, color=plt.rcParams["axes.edgecolor"], linewidth=1)
ax.set_yticks(y, order)
ax.xaxis.set_major_formatter(lambda v, _: f"{abs(v):.0f}%")
ax.set_xlabel("Share of responses, centred on neutral (disagree left, agree right)")
ax.legend(ncol=k, loc="upper center", bbox_to_anchor=(0.5, -0.15), fontsize=8)
plt.show()Needs pandas, numpy, matplotlib · reads likert-demo.csv · app theme from the optional codesplash helper
# Likert diverging bars — Codesplash Chart Lab (recipe "likert")
# controls: sort=net, 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("likert-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["Meaningful work"] = pd.Categorical(df["Meaningful work"].astype("string"), categories=["Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"])
df["Clear goals"] = pd.Categorical(df["Clear goals"].astype("string"), categories=["Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"])
df["Manager support"] = pd.Categorical(df["Manager support"].astype("string"), categories=["Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"])
df["Fair pay"] = pd.Categorical(df["Fair pay"].astype("string"), categories=["Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"])
df["Work–life balance"] = pd.Categorical(df["Work–life balance"].astype("string"), categories=["Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"])
df["Growth opportunities"] = pd.Categorical(df["Growth opportunities"].astype("string"), categories=["Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"])
ITEMS = ["Meaningful work", "Clear goals", "Manager support", "Fair pay", "Work–life balance", "Growth opportunities"]
LEVELS = ["Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"] # response order from the data dictionary
COLORS = ["#c95443", "#da8477", "#ced1d6", "#6691ca", "#2a69b5"] # disagree … neutral … agree
k = len(LEVELS)
mid = (k - 1) / 2 # with an odd number of levels the middle one is neutral
shares = {}
for item in ITEMS:
s = df[item].dropna().astype(str)
s = s[s.isin(LEVELS)]
shares[item] = s.value_counts().reindex(LEVELS, fill_value=0) / max(len(s), 1) # share of non-missing responses
shares = pd.DataFrame(shares).T * 100 # items × levels, percent
neg = shares[[l for j, l in enumerate(LEVELS) if j < mid]].sum(axis=1)
pos = shares[[l for j, l in enumerate(LEVELS) if j > mid]].sum(axis=1)
neutral = shares[[l for j, l in enumerate(LEVELS) if j == mid]].sum(axis=1)
net = pos - neg # net agreement
start = -(neg + neutral / 2) # half the neutral share on each side of zero
order = list(net.sort_values(ascending=False, kind="stable").index) # by net agreement
fig = go.Figure()
left = start.reindex(order)
for j, lvl in enumerate(LEVELS):
w = shares.loc[order, lvl]
fig.add_bar(y=order, x=w, base=left, orientation="h", name=lvl, marker_color=COLORS[j],
text=[f"{v:.0f}" if v >= 6 else "" for v in w], textposition="inside")
left = left + w
fig.update_layout(barmode="overlay", yaxis_autorange="reversed", xaxis_title="Share of responses (%)", legend_orientation="h")
fig.add_vline(x=0, line_width=1)
fig.show()Needs pandas, numpy, plotly · reads likert-demo.csv · app theme from the optional codesplash helper
# Likert diverging bars — Codesplash Chart Lab (recipe "likert")
# controls: sort=net, 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("likert-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["Meaningful work"]] <- factor(df[["Meaningful work"]], levels = c("Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"))
df[["Clear goals"]] <- factor(df[["Clear goals"]], levels = c("Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"))
df[["Manager support"]] <- factor(df[["Manager support"]], levels = c("Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"))
df[["Fair pay"]] <- factor(df[["Fair pay"]], levels = c("Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"))
df[["Work–life balance"]] <- factor(df[["Work–life balance"]], levels = c("Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"))
df[["Growth opportunities"]] <- factor(df[["Growth opportunities"]], levels = c("Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"))
update_geom_defaults("text", list(colour = "#131922")) # labels in the theme's text colour
items <- c("Meaningful work", "Clear goals", "Manager support", "Fair pay", "Work–life balance", "Growth opportunities")
LEVELS <- c("Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree") # response order from the data dictionary
COLORS <- c("#c95443", "#da8477", "#ced1d6", "#6691ca", "#2a69b5") # disagree … neutral … agree
k <- length(LEVELS)
mid <- (k - 1) / 2 # with an odd number of levels the middle one is neutral
shares <- t(sapply(items, function(it) {
v <- as.character(df[[it]])
v <- v[!is.na(v) & v %in% LEVELS]
100 * as.numeric(table(factor(v, levels = LEVELS))) / max(length(v), 1) # % of non-missing responses
}))
colnames(shares) <- LEVELS
j <- seq_len(k) - 1
neg <- rowSums(shares[, j < mid, drop = FALSE])
pos <- rowSums(shares[, j > mid, drop = FALSE])
neutral <- rowSums(shares[, j == mid, drop = FALSE])
net <- pos - neg # net agreement
start <- -(neg + neutral / 2) # half the neutral share on each side of zero
ord <- items[order(-net)] # by net agreement
segs <- do.call(rbind, lapply(items, function(it) {
x0 <- start[[it]] + c(0, cumsum(shares[it, ])[-k])
data.frame(item = it, level = factor(LEVELS, levels = LEVELS), xmin = x0, xmax = x0 + shares[it, ])
}))
segs$y <- match(segs$item, rev(ord)) # first item on top
p <- ggplot(segs) +
geom_rect(aes(xmin = xmin, xmax = xmax, ymin = y - 0.35, ymax = y + 0.35, fill = level)) +
geom_text(aes(x = (xmin + xmax) / 2, y = y, label = ifelse(xmax - xmin >= 6, round(xmax - xmin), "")), size = 2.5) +
geom_vline(xintercept = 0, linewidth = 0.4) +
scale_fill_manual(values = setNames(COLORS, LEVELS), name = NULL) +
scale_y_continuous(breaks = seq_along(ord), labels = rev(ord)) +
scale_x_continuous(labels = function(v) paste0(abs(v), "%")) +
labs(x = "Share of responses, centred on neutral (disagree left, agree right)", y = NULL) +
theme_cs +
theme(legend.position = "bottom")
print(p)Needs ggplot2 · reads likert-demo.csv · app theme from the optional codesplashr helper
-- Likert diverging bars — Codesplash Chart Lab (recipe "likert")
-- controls: sort=net, labels=true
-- response shares per item over non-missing responses on the declared scale
WITH long AS (
UNPIVOT (SELECT "Meaningful work"::VARCHAR AS "Meaningful work", "Clear goals"::VARCHAR AS "Clear goals", "Manager support"::VARCHAR AS "Manager support", "Fair pay"::VARCHAR AS "Fair pay", "Work–life balance"::VARCHAR AS "Work–life balance", "Growth opportunities"::VARCHAR AS "Growth opportunities" FROM read_csv('likert-demo.csv'))
ON "Meaningful work", "Clear goals", "Manager support", "Fair pay", "Work–life balance", "Growth opportunities"
INTO NAME item VALUE response
),
scale(response, j) AS (VALUES ('Strongly disagree', 0), ('Disagree', 1), ('Neutral', 2), ('Agree', 3), ('Strongly agree', 4))
SELECT item, response, j, count(*) AS n,
count(*) / sum(count(*)) OVER (PARTITION BY item) AS share
FROM long JOIN scale USING (response)
GROUP BY item, response, j
ORDER BY item, j;Needs duckdb · reads likert-demo.csv