library(tidyverse)
gapminder <- read_csv("data/gapminder_2010.csv")
penguins <- read_csv("data/penguins.csv")5 Ranking and ordering
- Make bar charts of counts and of values.
- Sort categories so the order carries meaning.
- Use horizontal bars, dot plots and lollipops for long category names.
- Show parts of a whole without a pie chart.
Alphabetical

Ranked

5.1 Load packages and data
import pandas as pd
from plotnine import *
gapminder = pd.read_csv("data/gapminder_2010.csv")
penguins = pd.read_csv("data/penguins.csv")5.2 Counts and values Core
There are two kinds of bar chart:
geom_bar()counts rows for you. Use it when each row is one observation.geom_col()draws a value you already have. Use it when you have calculated a number per category.
ggplot(penguins, aes(x = island)) +
geom_bar() +
labs(x = NULL, y = "Number of penguins")
p = (ggplot(penguins, aes(x="island"))
+ geom_bar()
+ labs(x="", y="Number of penguins")
+ theme(figure_size=(7, 3.5)))
p.show()
Now some values per category: mean life expectancy in each region.
region_le <- gapminder |>
group_by(region) |>
summarise(life_expectancy = mean(life_expectancy))
region_le# A tibble: 6 × 2
region life_expectancy
<chr> <dbl>
1 Americas 74.0
2 East Asia & Pacific 70.9
3 Europe & Central Asia 76.5
4 Middle East & North Africa 74.2
5 South Asia 69.4
6 Sub-Saharan Africa 60.0
region_le = (gapminder
.groupby("region", as_index=False)["life_expectancy"]
.mean())
region_le| region | life_expectancy | |
|---|---|---|
| 0 | Americas | 73.974848 |
| 1 | East Asia & Pacific | 70.872174 |
| 2 | Europe & Central Asia | 76.462500 |
| 3 | Middle East & North Africa | 74.241667 |
| 4 | South Asia | 69.377500 |
| 5 | Sub-Saharan Africa | 60.034324 |
5.3 Sort by value Core
By default, categories appear in alphabetical order, which is almost never what the reader needs. Sorting by value turns a lookup table into a ranking.
In R, fct_reorder() reorders a categorical variable by another variable.
ggplot(region_le, aes(x = life_expectancy, y = fct_reorder(region, life_expectancy))) +
geom_col() +
labs(x = "Mean life expectancy (years)", y = NULL)
Putting the categories on the y axis gives horizontal bars, so long names have room.
In Python, set the order by turning the column into an ordered category. plotnine draws horizontal bars with coord_flip().
order = region_le.sort_values("life_expectancy")["region"]
region_le["region"] = pd.Categorical(region_le["region"], categories=order)
p = (ggplot(region_le, aes(x="region", y="life_expectancy"))
+ geom_col()
+ coord_flip()
+ labs(x="", y="Mean life expectancy (years)")
+ theme(figure_size=(7, 3.5)))
p.show()
Note that with coord_flip() the x and y labels refer to the original axes, before flipping.
Sort by the value unless the categories have a natural order of their own, such as age groups, months, or dose levels. Then keep the natural order.
5.4 Dot plots and lollipops Core
Bars must start at zero, because we read their length. When all values are far from zero, or there are many categories, a dot plot uses less ink and lets the axis focus on the range that matters.
ggplot(region_le, aes(x = life_expectancy, y = fct_reorder(region, life_expectancy))) +
geom_segment(aes(x = 55, xend = life_expectancy, yend = region), colour = "grey70") +
geom_point(size = 4, colour = "#003E72") +
labs(x = "Mean life expectancy (years)", y = NULL)
p = (ggplot(region_le, aes(x="region", y="life_expectancy"))
+ geom_segment(aes(xend="region", y=55, yend="life_expectancy"), color="#B3B3B3")
+ geom_point(size=4, color="#003E72")
+ coord_flip()
+ labs(x="", y="Mean life expectancy (years)")
+ theme(figure_size=(7, 3.5)))
p.show()
This is a lollipop chart: a dot plot with a thin line to guide the eye. Because the stick starts at 55 rather than 0, the length of the stick means nothing on its own. That is fine for dots and lollipops, but not for bars.
5.5 Top and bottom Extension
With many categories, show only the ones that matter for the message, and say so in the title.
gapminder |>
slice_max(child_mortality, n = 10) |>
ggplot(aes(x = child_mortality, y = fct_reorder(country, child_mortality))) +
geom_col(fill = "#D6083B") +
labs(title = "The ten countries with the highest child mortality in 2010",
x = "Deaths before age 5 per 1,000 births", y = NULL)
top10 = gapminder.nlargest(10, "child_mortality").copy()
order = top10.sort_values("child_mortality")["country"]
top10["country"] = pd.Categorical(top10["country"], categories=order)
p = (ggplot(top10, aes(x="country", y="child_mortality"))
+ geom_col(fill="#D6083B")
+ coord_flip()
+ labs(title="The ten countries with the highest child mortality in 2010",
x="", y="Deaths before age 5 per 1,000 births")
+ theme(figure_size=(7, 3.8)))
p.show()
5.6 Parts of a whole Extension
Pie charts encode values as angles and areas, which we compare poorly. For shares, a single stacked bar or a set of sorted bars is usually clearer. Here is the share of countries in each income group, by region.
gapminder |>
mutate(income_groups = fct_relevel(income_groups, "low_income", "lower_middle_income",
"upper_middle_income", "high_income")) |>
ggplot(aes(y = region, fill = income_groups)) +
geom_bar(position = "fill") +
scale_x_continuous(labels = scales::label_percent()) +
scale_fill_brewer(palette = "Blues",
labels = c("Low", "Lower middle", "Upper middle", "High")) +
labs(x = "Share of countries", y = NULL, fill = "Income group")
levels = ["low_income", "lower_middle_income", "upper_middle_income", "high_income"]
gapminder["income_groups"] = pd.Categorical(gapminder["income_groups"], categories=levels)
p = (ggplot(gapminder, aes(x="region", fill="income_groups"))
+ geom_bar(position="fill")
+ coord_flip()
+ scale_y_continuous(labels=lambda breaks: [f"{b:.0%}" for b in breaks])
+ scale_fill_brewer(palette="Blues",
labels=["Low", "Lower middle", "Upper middle", "High"])
+ labs(x="", y="Share of countries", fill="Income group")
+ theme(figure_size=(7, 3.8)))
p.show()
Income groups have a natural order, so we set it explicitly and used a sequential palette (light to dark) to match. See Colour with purpose.
5.7 Exercises
Level:
Make a horizontal bar chart of median income per person by region, sorted from highest to lowest.
gapminder |>
group_by(region) |>
summarise(income = median(income_per_person)) |>
ggplot(aes(x = income, y = fct_reorder(region, income))) +
geom_col(fill = "#0072CF") +
scale_x_continuous(labels = scales::label_dollar(accuracy = 1)) +
labs(x = "Median income per person", y = NULL)
income = gapminder.groupby("region", as_index=False)["income_per_person"].median()
order = income.sort_values("income_per_person")["region"]
income["region"] = pd.Categorical(income["region"], categories=order)
p = (ggplot(income, aes(x="region", y="income_per_person"))
+ geom_col(fill="#0072CF")
+ coord_flip()
+ scale_y_continuous(labels=lambda breaks: [f"${b:,.0f}" for b in breaks])
+ labs(x="", y="Median income per person")
+ theme(figure_size=(7, 3.5)))
p.show()
In R, sorting with fct_reorder() puts the largest value at the top of a horizontal bar chart, because the y axis counts upwards from the bottom.
Level:
Make a dot plot of mean bill length per penguin species. Then make it as a bar chart. Which works better, and why?
penguins |>
group_by(species) |>
summarise(bill = mean(bill_length_mm, na.rm = TRUE)) |>
ggplot(aes(x = bill, y = fct_reorder(species, bill))) +
geom_point(size = 4) +
labs(x = "Mean bill length (mm)", y = NULL)
bill = penguins.groupby("species", as_index=False)["bill_length_mm"].mean()
order = bill.sort_values("bill_length_mm")["species"]
bill["species"] = pd.Categorical(bill["species"], categories=order)
p = (ggplot(bill, aes(x="species", y="bill_length_mm"))
+ geom_point(size=4)
+ coord_flip()
+ labs(x="", y="Mean bill length (mm)")
+ theme(figure_size=(7, 3)))
p.show()
All three means are between 38 and 49 mm. As bars starting from zero, the bars look almost the same length. As dots, the axis can zoom to the range of the data and the differences are clear. Better still would be to show the full distribution, as in Distributions.
5.8 Summary
geom_bar()counts rows;geom_col()draws values you have calculated.- Sort categories by value unless they have a natural order.
- Horizontal bars give long labels room.
- Bars start at zero; dot plots and lollipops do not need to.
- Prefer sorted or stacked bars to pie charts for comparing shares.