ggplot2 Piechart



A pie chart is a circle divided into sectors that each represent a proportion of the whole. This page explains how to build one with the ggplot2 package.

Pie Chart section Why you should not do it

Most basic pie chart


ggplot2 does not offer any specific geom to build piecharts. The trick is the following:

  • input data frame has 2 columns: the group names (group here) and its value (value here)
  • build a stacked barchart with one bar only using the geom_bar() function.
  • Make it circular with coord_polar()

The result is far from optimal yet, keep reading for improvements.

# Load ggplot2
library(ggplot2)

# Create Data
data <- data.frame(
  group=LETTERS[1:5],
  value=c(13,7,9,21,2)
)

# Basic piechart
ggplot(data, aes(x="", y=value, fill=group)) +
  geom_bar(stat="identity", width=1) +
  coord_polar("y", start=0)

Improve appearance


Previous version looks pretty bad. We need to:

  • remove useless numeric labels
  • remove grid and grey background

It’s better now, just need to add labels directly on chart.

# Load ggplot2
library(ggplot2)

# Create Data
data <- data.frame(
  group=LETTERS[1:5],
  value=c(13,7,9,21,2)
)

# Basic piechart
ggplot(data, aes(x="", y=value, fill=group)) +
  geom_bar(stat="identity", width=1, color="white") +
  coord_polar("y", start=0) +
  
  theme_void() # remove background, grid, numeric labels

Adding labels with geom_text()


The tricky part is to compute the y position of labels using this weird coord_polar transformation.

# Load ggplot2
library(ggplot2)
library(dplyr)

# Create Data
data <- data.frame(
  group=LETTERS[1:5],
  value=c(13,7,9,21,2)
)

# Compute the position of labels
data <- data %>% 
  arrange(desc(group)) %>%
  mutate(prop = value / sum(data$value) *100) %>%
  mutate(ypos = cumsum(prop)- 0.5*prop )

# Basic piechart
ggplot(data, aes(x="", y=prop, fill=group)) +
  geom_bar(stat="identity", width=1, color="white") +
  coord_polar("y", start=0) +
  theme_void() + 
  theme(legend.position="none") +
  
  geom_text(aes(y = ypos, label = group), color = "white", size=6) +
  scale_fill_brewer(palette="Set1")

Related chart types


Grouped and Stacked barplot
Treemap
Doughnut
Pie chart
Dendrogram
Circular packing



Contact

This document is a work by Yan Holtz. Any feedback is highly encouraged. You can fill an issue on Github, drop me a message on Twitter, or send an email pasting yan.holtz.data with gmail.com.

Github Twitter