Contents/ Part III · Visualizing Data/ Chapter 14

Charts for Categorical Data

A chart is an argument made in pictures. This chapter is about the honest ones for categories: the bar chart and its variants, the pie chart and its traps, and the axis tricks that quietly lie.

⏱️ ~12 min read
🐍 Notebook included
📊 Chapter 14

Describing Data turned data into numbers. Visualizing Data turns it into pictures. We start where most real datasets do: categories, and the question of how a total splits across them.

A chart for categorical data shows how a whole breaks down across distinct groups, as counts, frequencies, or proportions. Each category is a label, not a number on a scale.
1

What Categorical Charts Show

Recall the levels of measurement from the Levels of Measurement chapter. Whether a category is ordered changes how you may draw it:

Nominal

Unordered labels: browser, country, product. You may freely sort bars by value.

Ordinal

Ordered labels: S/M/L/XL, survey ratings, age bands. Keep the natural order; do not resort.

Categorical charts answer "how many, or what share, in each group?" That is a different question from the numerical charts in the Charts for Numerical Data chapter, which describe the distribution of a continuous quantity.

2

The Bar Chart: the Workhorse

The bar chart is the default for a reason. It encodes each amount as a bar length on a common baseline, and length on a shared scale is the encoding our eyes read most accurately. A few habits separate a good bar chart from a misleading one.

Vertical or horizontal

Go horizontal when labels are long or there are many categories; it reads like a ranked list, no rotated text.

Sort, when you can

For nominal categories, sort by value so comparisons are instant. Keep natural order for ordinal data.

Mind the gaps

Bars sit apart, with gaps, to signal distinct categories. Touching bars mean a histogram (next section).

Start at zero

A bar's length must be proportional to its value, so the axis has to begin at zero. This one is non-negotiable.

🚨
The truncated axis: how a bar chart lies

Cut the baseline above zero and a small difference balloons into a huge one. The two charts below plot the same two numbers, 35% and 39.6%. Only the axis changed.

Truncated axis (misleading) 34% 40% 35% 39.6% Zero baseline (honest) 0% 40% 35% 39.6% Same numbers. The left chart manufactures a gap that is not in the data.

For a second categorical variable you have two layouts, and they answer different questions:

Grouped (clustered)

Sub-bars side by side on one baseline. Best to compare the series precisely. Gets cluttered past about five series.

Stacked

Segments stacked into one bar. Best to read the total per category. Weakness: only the bottom segment touches the baseline, so the floating upper segments are hard to compare.

3

Bar Chart vs. Histogram

They look like cousins, and that resemblance trips up almost everyone. The quickest tell: bar charts have gaps; histograms touch.

Bar chart · categories ABCD gaps between bars · reorderable Histogram · continuous 02050 bars touch · fixed numeric order
Bar chartHistogram
BarsSeparated by gapsTouch (no gaps)
X-axisCategory labelsContinuous number line, binned
ReorderingFine, sort by value or logicFixed, bins stay in numeric order
AnswersHow many in each category?How is this quantity distributed?
4

Pie Charts & Honest Design

The pie chart shows parts of a whole, and the slices must sum to 100%. The trouble is perceptual: it asks the eye to compare angles and areas, which we judge far worse than lengths on a common scale. That is why a sorted bar chart usually wins.

👁️
We read length better than angle

Classic perception research (Cleveland & McGill) ranks how accurately we decode visual cues: position and length on a common scale come first; angle and area are near the bottom. A bar uses the best cue, a pie uses some of the worst.

If you do reach for a pie, keep it disciplined:

Few slices

About five at most. Fold the small ones into "Other".

Sorted & whole

Order by size and make sure the slices actually sum to 100%.

Direct labels

Put the name and value on each slice; skip the legend hunt.

No 3D or explode

3D perspective and exploded slices distort area. Always flat.

🧰
Better alternatives worth knowing

For many categories, a dot plot (a dot per category on a common axis) is clean and, unlike a bar, needs no zero baseline. A treemap handles hierarchical part-to-whole; a pictograph of repeated icons suits lay audiences, as long as you scale by adding icons, never by enlarging one (area grows as the square of size and exaggerates the count).

🎨
Design that respects the reader

Strip the chartjunk: heavy gridlines, dark borders, 3D, and decorative color all add ink without adding information (Tufte's data-ink idea). Use a qualitative palette of distinct hues for categories, and do not rely on color alone, around 1 in 12 men has a color-vision deficiency, so add labels or position and use a colorblind-safe palette. Gray the context and let one color carry the point.

🤖
Why this matters for data science

Category breakdowns are the bread and butter of exploratory analysis (value_counts().plot.bar(), seaborn's countplot) and of every stakeholder deck. The chart you choose is an argument about the data. Make it an honest one: the right encoding, a zero baseline, and a fair ordering.

5

Categorical Charts in Machine Learning & AI

Bar charts of categories are not just for reports, they are working tools in a modeling pipeline. Some of the most important diagnostic plots in machine learning are categorical charts by another name.

Categorical chartWhere it shows up in MLWhat it tells you
Class-balance barA bar chart of the target's categories before trainingReveals imbalance, the first thing to check before trusting accuracy
Confusion matrixA grid of predicted vs actual classes, shaded by countThe standard scorecard for a classifier, a two-way categorical chart
Cardinality barCounts per level of a categorical featureFlags high-cardinality columns that need frequency or target encoding, not one-hot
🤖
The grouped bar is a peek at a relationship

A grouped bar of the target across a categorical feature (satisfaction by work mode, say) is exactly the signal a model will try to learn. If the bars differ sharply across groups, that feature carries predictive information, the visual version of what a chi-square test or a tree split confirms.

6

Real-World Example: An Employee Survey

Categorical charts turn a survey of 400 employees into something you can act on. A simple bar chart ranks the departments by headcount; a grouped bar of satisfaction by work mode tells the real story, remote and hybrid staff report High satisfaction far more often than onsite staff. The companion notebook draws the bar, grouped-bar, and stacked-bar versions.

📂 Dataset · charts-for-categorical-data--employee_survey.xlsx

One row per employee: employee_id, department (5 teams), work_mode (Remote, Hybrid, Onsite), and satisfaction (Low, Medium, High). Every column is categorical, so the tools are counts and bars, never averages.

🐍

Bring it to life in Python

The companion notebook builds bar charts from counts, sorts and flips them, contrasts grouped versus stacked layouts, recreates the truncated-axis deception side by side with an honest version, and shows why a sorted bar reads more clearly than a pie.

📓 View Notebook (code & outputs) ▶ Open in Colab ⬇ View / Download on GitHub

View opens the rendered notebook instantly (no setup). Open in Colab runs & edits it live in your browser. To run locally, install numpy, pandas, matplotlib and launch jupyter notebook.

🎓 Key Takeaways

  • Categorical charts show how a whole splits across groups; sort nominal categories, keep ordinal order.
  • The bar chart is the default; bars have gaps and must start at zero.
  • A truncated axis exaggerates differences, the most common way a bar chart misleads.
  • Bars have gaps, histograms touch: categories vs. binned continuous data.
  • Pies read poorly (angle beats no one); prefer a sorted bar, and keep design honest and clutter-free.
7

Practice Challenges

Five short challenges, beginner to intermediate. Try them on paper or in Python before checking the solutions.

1

Sorted bars

From a set of pet-ownership counts, draw a horizontal bar chart sorted by value. Why is horizontal and sorted a good choice, and would sorting be fair if the categories were ordinal?

Hint: sort_values() then barh; nominal categories may be reordered.
2

Spot the lie

Two satisfaction scores, 82 and 86, are charted with the y-axis starting at 80. Redraw it honestly and quantify how much the truncated axis exaggerates the gap.

Hint: compare bar-height ratio under ylim(80,…) vs a zero baseline.
3

Bar or histogram?

For each, pick the chart and name the visual tell: (a) counts of favorite ice-cream flavor; (b) the distribution of 500 customers' ages.

Hint: categorical vs. continuous; gaps vs. touching bars.
4

Pie to bar

A survey with eight genre categories is shown as a pie and readers cannot rank the middle slices. Convert it to a sorted bar chart and explain why the bar is clearer.

Hint: too many slices, near-equal angles; bars share a common scale.
5

Grouped vs stacked

For two product lines across three regions, make both a grouped and a stacked bar chart. Which answers "which line sells more in each region?" and which answers "what is each region's total?"

Hint: grouped shares a baseline; stacked sums to the total.
Check your work

A fully-worked solutions notebook walks through all five challenges in the same visual style. Try them yourself first, then compare.

📓 View Solutions ▶ Open Solutions in Colab ⬇ View / Download on GitHub
8

Quiz: Test Yourself

Eight quick questions on categorical charts. Answer them, hit Check Answers, and keep refining until you score 100%. Your progress is saved, so you can hop back to the chapter and return anytime.