Skip to main content

Introducing ggpyramid - Population Pyramids as ggplot2 Layers

ggpyramid 0.1.0 is on CRAN. It draws population pyramids from ordinary ggplot2 layers, so one plot can count records or sum tables, show shares, label its bars and compare two populations, and still be faceted and themed like any other ggplot.

R
packages
release
CRAN
ggplot2
data visualization
demography
Author

Matan Hakim

Published

December 2, 2026

I’m currently taking a course on research methods in demography, and population pyramids turn up in nearly every session: two bar charts set back to back, men on one side and women on the other, with the youngest age group at the bottom and the oldest at the top. A single pyramid carries a country’s fertility, mortality, migration and baby booms in one shape, which is why demographers draw them all the time. So when I sat down to draw one in ggplot2, I assumed a dedicated tool would be waiting for me, and was surprised to find mostly a recipe instead: negate the counts of one sex, relabel the axis with abs(), compute symmetric limits by hand, flip the coordinates, and hope that nothing you add to the plot afterward notices the trick.

So I spent a while reading how statistical agencies and R users actually build pyramids, went through the existing packages to see where each of them stops, and then built the package I had been hoping to find. I’m happy to announce that ggpyramid 0.1.0 is now on CRAN. ggpyramid is a ggplot2 extension in which a population pyramid is made of ordinary ggplot2 components, so scales, facets, themes and further layers work exactly as they do anywhere else in ggplot2.

install.packages("ggpyramid")
library(ggplot2)
library(ggpyramid)
library(dplyr)

A first pyramid

The package ships with europe_pop, the population of France, Ireland, Italy and Poland on January 1, 2004 and 2024, by five-year age group and sex, from Eurostat. It has the shape most published population data comes in, one row per country, year, age group and sex:

head(europe_pop)
  country year   age  sex population
1  France 2004   0-4 Male    2003057
2  France 2004   5-9 Male    1955935
3  France 2004 10-14 Male    2029376
4  France 2004 15-19 Male    2089909
5  France 2004 20-24 Male    2005783
6  France 2004 25-29 Male    1918838

geom_pyramid() draws the bars and coord_pyramid() draws the axes. The mapping is the one you would write for any horizontal bar chart – the population on x, the age group on y and sex on fill – and the package takes care of the mirroring:

france <- europe_pop |> filter(country == "France", year == 2024)

ggplot(france, aes(x = population, y = age, fill = sex)) +
  geom_pyramid(width = 1, color = "white") +
  scale_x_continuous(labels = scales::label_comma()) +
  coord_pyramid(age_axis = "center") +
  labs(x = NULL, y = NULL, fill = NULL) +
  theme_pyramid()
A population pyramid of France in 2024, with men in red on the left and women in teal on the right, five-year age groups from 0-4 at the bottom to 85+ at the top, and the age labels in a gap between the two halves. The value axis reads 0 to 2,000,000 on both sides without minus signs.
Figure 1

Three details in this plot are things the usual recipe makes you do by hand. The value axis is labeled without a minus sign on the left; the two halves share one symmetric range, so a bar of a given length means the same number on either side; and the age labels sit in a gap between the halves, where they can’t hide a bar. The data went in exactly as it was, with no column negated beforehand, and theme_pyramid() adds a minimal theme with the legend on top, where it reads as a heading for the two sides.

Records or tables, counts or shares

Population data comes in two shapes. Published statistics arrive as aggregated tables, one row per age group and sex with a count, while surveys and administrative files arrive as individual records, one row per person. geom_pyramid() takes both: it sums x within each age group when you map it and counts rows when you leave it out, and weight multiplies either, which is where survey weights go.

The denominator argument turns counts into shares, of everyone in the panel with "total" or of each side with "side". Shares are what make populations of different sizes comparable, and they are the natural way to check a sample against the population it was drawn from, a routine step in survey work. To show both features at once, here is a simulated survey of 1,500 respondents drawn from Ireland’s 2024 population, one row per person:

ireland <- europe_pop |> filter(country == "Ireland", year == 2024)

set.seed(2026)
survey <- ireland |>
  slice_sample(n = 1500, replace = TRUE, weight_by = population) |>
  select(age, sex)

head(survey)
    age    sex
1 25-29 Female
2 30-34   Male
3 45-49 Female
4 15-19   Male
5 30-34   Male
6 40-44 Female

The bars count the respondents and the outline sums the published population, and each layer is divided by its own total:

ggplot(survey, aes(y = age, fill = sex)) +
  geom_pyramid(denominator = "total", width = 1, color = "white") +
  geom_pyramid_outline(
    data = ireland,
    aes(x = population),
    denominator = "total",
    linewidth = 0.6
  ) +
  scale_x_continuous(labels = scales::label_percent()) +
  coord_pyramid(age_axis = "center") +
  labs(
    x = NULL, y = NULL, fill = "Survey (n = 1,500)",
    caption = "The outline shows Ireland's 2024 population."
  ) +
  theme_pyramid()
A population pyramid of 1,500 simulated survey respondents from Ireland, drawn as bars showing the percentage of the sample in each age group and sex, with a black stepped outline showing the same shares for Ireland's 2024 population. The bars and the outline mostly agree, with small gaps in both directions.
Figure 2

Where a bar stops short of the outline, that age group and sex is under-represented in the sample, and where it runs past it, over-represented. In a simple random sample of this size the gaps are sampling noise, which is itself worth seeing; in a real survey they are the first place to look before deciding on weights.

Where the age axis goes, and which side is on the left

Statistical agencies don’t agree on where the age labels belong. The US Census Bureau’s design standard for population pyramids recommends labeling the age axis on both sides and advises against labels in the center, while many published pyramids put them right down the middle. coord_pyramid() leaves the choice to you: age_axis takes "left" (the default), "right", "both" or "center", and gap sets the width of the space between the halves.

Which sex goes on the left is a convention too. Most official sources put men on the left, which is what you get when Male is the first level of the side variable, and left in coord_pyramid() chooses the other side by name. Since it lives in the coordinate system it applies to every layer of the plot at once, so labels and outlines can’t drift to a different side from their bars:

ggplot(france, aes(x = population, y = age, fill = sex)) +
  geom_pyramid(width = 1, color = "white") +
  scale_x_continuous(
    labels = scales::label_number(scale = 1e-6, suffix = "M")
  ) +
  scale_fill_discrete(breaks = c("Female", "Male")) +
  coord_pyramid(left = "Female", age_axis = "both", gap = 0.08) +
  labs(x = NULL, y = NULL, fill = NULL) +
  theme_pyramid()
The same pyramid of France in 2024 with women on the left and men on the right, age labels on both outer sides, and a narrow gap in the middle where each half starts from its own zero.
Figure 3

The legend keeps the order of the factor levels, which is why breaks in the fill scale reorders it to match.

Comparing populations

The comparison demographers draw most often is between two moments in time, and geom_pyramid_outline() traces a second pyramid as a stepped line over the bars. Here Italy in 2024 is drawn as bars and Italy in 2004 as the outline:

italy <- europe_pop |> filter(country == "Italy")

p_italy <- ggplot(italy, aes(x = population, y = age, fill = sex)) +
  geom_pyramid(data = filter(italy, year == 2024), width = 1, alpha = 0.8) +
  geom_pyramid_outline(data = filter(italy, year == 2004), linewidth = 0.6) +
  scale_x_continuous(
    labels = scales::label_number(scale = 1e-6, suffix = "M")
  ) +
  coord_pyramid(age_axis = "center") +
  labs(
    x = NULL, y = NULL, fill = "2024",
    caption = "The outline shows 2004."
  ) +
  theme_pyramid()

p_italy
A population pyramid of Italy in 2024 drawn as bars, with a black stepped outline showing Italy in 2004. The 2004 outline bulges at ages 30 to 44, while the 2024 bars bulge at ages 50 to 59; the 2024 bars are narrower than the outline below age 15 and much wider at 85+.
Figure 4

Twenty years of Italian demography fit in one picture. The large cohorts born in the mid-1960s, who were 35-39 in 2004 and the biggest age group in the country, are now 55-59 and still the biggest; the 85+ group has more than doubled, from 1.1 to 2.3 million; and every age group under 15 is smaller than it was, with the youngest, 0-4, down by almost a quarter.

Since every layer takes its own data, the same pattern compares a region with the whole country, or a sample with its population, as in the survey above. Facets work as usual too, and with denominator = "total" each panel is divided by its own total, so countries of very different sizes share one readable scale:

ggplot(europe_pop, aes(x = population, y = age, fill = sex)) +
  geom_pyramid(denominator = "total") +
  scale_x_continuous(labels = scales::label_percent()) +
  coord_pyramid() +
  facet_grid(year ~ country) +
  labs(x = "Share of the population", y = NULL, fill = NULL) +
  theme_pyramid()
A grid of eight population pyramids, one for each of France, Ireland, Italy and Poland in 2004 (top row) and 2024 (bottom row), each showing the percentage of that country's population in each age group and sex on a shared scale.
Figure 5

Labels and subgroups

geom_pyramid_text() writes the value of each bar at its end. It aggregates the data exactly as the bars do, so it needs no extra mapping, and the labels go "outside" the bars by default or "inside" them, formatted by any labeling function from scales:

ggplot(ireland, aes(x = population, y = age, fill = sex)) +
  geom_pyramid(denominator = "side") +
  geom_pyramid_text(
    denominator = "side",
    labels = scales::label_percent(accuracy = 0.1),
    size = 2.6
  ) +
  scale_x_continuous(
    labels = scales::label_percent(),
    expand = expansion(mult = 0.15)
  ) +
  coord_pyramid(age_axis = "center") +
  labs(x = "Share of each sex", y = NULL, fill = NULL) +
  theme_pyramid()
A population pyramid of Ireland in 2024 showing each age group as a percentage of its own sex, with the percentage written at the outer end of every bar on both sides and the age labels in a gap at the center.
Figure 6

When fill should show something other than the side – a region, a place of birth, a population group – map the side explicitly with the side aesthetic, and the subgroups stack within each side. Here the 2024 populations of Ireland and Poland are stacked within each sex:

europe_pop |>
  filter(year == 2024, country %in% c("Ireland", "Poland")) |>
  ggplot(aes(x = population, y = age, fill = country, side = sex)) +
  geom_pyramid(width = 1) +
  scale_x_continuous(
    labels = scales::label_number(scale = 1e-6, suffix = "M")
  ) +
  coord_pyramid(age_axis = "center") +
  labs(x = NULL, y = NULL, fill = NULL) +
  theme_pyramid()
A population pyramid in which each sex's bars are split into two stacked segments, Ireland and Poland in 2024, with men on the left and women on the right and the age labels at the center.
Figure 7

How ggpyramid differs from the alternatives

Before writing any code I went through what already exists, and it’s worth laying out fairly, because each of these tools does something well:

Tool Approach Where it stops
The manual recipe Negate one side, labels = abs, symmetric limits by hand, often coord_flip() Every layer sees the negative numbers, so a geom_text() label prints “-1,760,139” unless you remember to wrap it in abs() too, and limits computed by hand break once you facet or add a layer
apyramid age_pyramid() returns a complete ggplot from one call Adding your own scale replaces the one that holds its labels and limits, so the left side turns negative and the range is no longer symmetric
ggcharts pyramid_chart() joins two plots with patchwork The result is two separate plots, so a layer, scale or facet you add applies to the last of them only
ggpol facet_share(), a facet with a shared axis Archived on CRAN in December 2025
ggstats geom_pyramid(), a true ggplot2 layer The side comes from a category’s position in a diverging stack, as shown below

ggstats is the closest relative, and the one I learned the most from. Its geom_pyramid(), added alongside geom_likert() and geom_diverging(), is a genuine ggplot2 layer that mirrors the bars in a position adjustment, which is the design ggpyramid uses as well. The difference is where the side comes from. position_diverging() stacks the categories of each age group and centers the stack so that half of the categories fall on each side of zero, which is exactly right for a Likert scale, where the neutral answer belongs on the zero line. In a pyramid it means that the side depends on how many categories each age group happens to have, so when an age group holds only one sex – no men aged 85+ in a small town or a small sample – the lone bar is centered across the middle, half of it on the men’s side, without a warning. To see it, drop the men aged 85+ from the French table:

no_old_men <- france |> filter(!(age == "85+" & sex == "Male"))

# ggstats is not attached here, so its default position is passed explicitly
p_ggstats <- ggplot(no_old_men, aes(y = age, fill = sex, weight = population)) +
  ggstats::geom_pyramid(position = ggstats::position_diverging()) +
  scale_x_continuous(labels = ggstats::label_percent_abs()) +
  labs(title = "ggstats::geom_pyramid()", x = NULL, y = NULL, fill = NULL)

p_ggpyramid <- ggplot(no_old_men, aes(x = population, y = age, fill = sex)) +
  ggpyramid::geom_pyramid(denominator = "total") +
  scale_x_continuous(labels = scales::label_percent()) +
  coord_pyramid() +
  labs(title = "ggpyramid::geom_pyramid()", x = NULL, y = NULL, fill = NULL)

library(patchwork)
Warning: package 'patchwork' was built under R version 4.5.3
p_ggstats + p_ggpyramid + plot_layout(guides = "collect") & theme_pyramid()
Two population pyramids of France in 2024 from which the men aged 85+ were removed. On the left, drawn with ggstats, the women aged 85+ bar is centered on zero, so half of it extends into the men's side. On the right, drawn with ggpyramid, the women aged 85+ bar sits entirely on the women's side and the men's side is empty for that age group.
Figure 8

ggstats documents this case and fixes it with complete = "fill", which is not the default for its geom_pyramid(). In ggpyramid the side is a variable rather than a position, so a missing row simply means a missing bar, and the same distinction is what lets ggpyramid color the bars by one variable while splitting them by another, which ggstats can only express by merging both into a single fill variable. ggpyramid also adds the parts of a pyramid that live beyond the bars: the age axis in the center, the outline layer, labels that know their side, and the left side chosen by name. If you use both packages, note that each exports a geom_pyramid() and a geom_pyramid_text(), so the one you load last wins, and ggpyramid::geom_pyramid() settles it.

Under the hood

The design comes down to splitting the work between two ggplot2 components. position_pyramid(), the default position of every ggpyramid layer, owns correctness: inside the plot it makes the values on the left side negative and stacks subgroups within each side, while the data you pass in stays as it is. coord_pyramid() owns presentation: the absolute labels, the symmetric range, the placement of the age axis and the gap at the center.

That split has two consequences I care about. If you replace coord_pyramid() with another coordinate system, the plot remains correct and only the presentation goes away, and scale_x_pyramid() brings the absolute labels back. And because the mirroring is done by a position rather than by a particular geom, any ggplot2 layer can join a pyramid with position = "pyramid". Here Italy’s 2004 population is drawn as points over the 2024 bars, with nothing more than geom_point():

ggplot(mapping = aes(x = population, y = age)) +
  geom_pyramid(
    data = filter(italy, year == 2024),
    aes(fill = sex), width = 1, alpha = 0.5
  ) +
  geom_point(
    data = filter(italy, year == 2004),
    aes(color = sex), position = "pyramid", size = 2
  ) +
  scale_x_continuous(
    labels = scales::label_number(scale = 1e-6, suffix = "M")
  ) +
  coord_pyramid(age_axis = "center") +
  labs(x = NULL, y = NULL, fill = "2024", color = "2004") +
  theme_pyramid()
A population pyramid of Italy in 2024 drawn as pale bars, with a dot for each age group and sex marking the 2004 population. The dots sit beyond the bars for most age groups under 45 and inside them from 45 upward.
Figure 9

The same holds for geom_col(), geom_text() or error bars. Vertical pyramids work too, with age on x, scale_y_pyramid() for the value axis and theme_pyramid(flipped = TRUE), and the ggproto classes behind the layers are exported for anyone who wants to build new ones on top of them. The one thing to keep in mind is that limits and reference lines on the left side are given as negative numbers, since that is where the left side actually lives inside the plot: geom_vline(xintercept = c(-1e6, 1e6)).

A skill for your AI coding agent

ggpyramid is too new to appear in the training data of most of today’s language models, so an AI coding agent asked for a pyramid has no reason to know it exists, and may well mix it up with the geom_pyramid() from ggstats when told about it. Having argued a few months ago that authoring a skill is one sentence away, it would have been a little awkward not to ship one. The ggpyramid repository includes an agent skill, a single SKILL.md file that teaches the agent how the package divides the work, how to put age groups in order and handle record-level data, how to choose the side and the denominator, and which mistakes to avoid. You can install it with the skills CLI, which works with Claude Code, Codex, Cursor, Posit Assistant and many other agents:

npx skills add matanhakim/ggpyramid

Or copy the skills/ggpyramid folder into your agent’s skills directory, ~/.claude/skills/ for Claude Code.

I tested the skill on a handful of tasks before publishing it, each run once with the skill and once without. When the request names ggpyramid, an agent without the skill gets there anyway by reading the help pages, only more slowly. The difference shows when the package isn’t named: asked for a population pyramid of Poland with 2004 drawn for comparison, the agent without the skill built it by hand, in 115 lines of rectangles, offsets and hand-set breaks, while the agent with the skill wrote 54 lines of ggpyramid and finished in about two thirds of the time.

What’s next

This is a first release, and feedback from people who draw pyramids in their own work is the most useful thing it can get. A few additions are already on my list, including highlighting the surplus of one sex in each age group, a secondary axis for year of birth, and labels for birth cohorts. If something you need is missing, or something behaves in a way you didn’t expect, please open an issue.

Resources