install.packages("ggpyramid")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.
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()
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.
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 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
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()
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()
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()
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()
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()
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/ggpyramidOr 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
- Documentation: https://matanhakim.github.io/ggpyramid/
- Source code: https://github.com/matanhakim/ggpyramid
- CRAN page: https://CRAN.R-project.org/package=ggpyramid
- Agent skill: https://github.com/matanhakim/ggpyramid/tree/main/skills/ggpyramid
- Bug reports: https://github.com/matanhakim/ggpyramid/issues