How to Create a Pie Chart in R using GGPLot2



How to Create a Pie Chart in R using GGPLot2

This article describes how to create a pie chart and donut chart using the ggplot2 R package. Pie chart is just a stacked bar chart in polar coordinates.

The function coord_polar() is used to produce pie chart from a bar plot.



Contents:

Related Book

GGPlot2 Essentials for Great Data Visualization in R

Prerequisites

Load required packages

library("ggplot2")  # Data visualization
library("dplyr")    # Data manipulation

Data preparation

  1. Create titanic passengers count dataset:
count.data <- data.frame(
  class = c("1st", "2nd", "3rd", "Crew"),
  n = c(325, 285, 706, 885),
  prop = c(14.8, 12.9, 32.1, 40.2)
)
count.data
##   class   n prop
## 1   1st 325 14.8
## 2   2nd 285 12.9
## 3   3rd 706 32.1
## 4  Crew 885 40.2
  1. Compute the position of the text labels as the cumulative sum of the proportion:
  1. Arrange the grouping variable (class) in descending order. This is important to compute the y coordinates of labels.
  2. To put the labels in the center of pies, we’ll use cumsum(prop) - 0.5*prop as label position.
# Add label position
count.data <- count.data %>%
  arrange(desc(class)) %>%
  mutate(lab.ypos = cumsum(prop) - 0.5*prop)
count.data
##   class   n prop lab.ypos
## 1  Crew 885 40.2     20.1
## 2   3rd 706 32.1     56.3
## 3   2nd 285 12.9     78.8
## 4   1st 325 14.8     92.6

Pie chart

  • Create the pie charts using ggplot2 verbs. Key function: geom_bar() + coord_polar().
  • Add text labels: geom_text()
  • Change fill color manually: scale_color_manual()
  • Apply theme_void() to remove axes, background, etc
mycols <- c("#0073C2FF", "#EFC000FF", "#868686FF", "#CD534CFF")

ggplot(count.data, aes(x = "", y = prop, fill = class)) +
  geom_bar(width = 1, stat = "identity", color = "white") +
  coord_polar("y", start = 0)+
  geom_text(aes(y = lab.ypos, label = prop), color = "white")+
  scale_fill_manual(values = mycols) +
  theme_void()

Donut chart

Donut chart chart is just a simple pie chart with a hole inside.

The only difference between the pie chart code is that we set: x = 2 and xlim = c(0.5, 2.5) to create the hole inside the pie chart. Additionally, the argument width in the function geom_bar() is no longer needed.

ggplot(count.data, aes(x = 2, y = prop, fill = class)) +
  geom_bar(stat = "identity", color = "white") +
  coord_polar(theta = "y", start = 0)+
  geom_text(aes(y = lab.ypos, label = prop), color = "white")+
  scale_fill_manual(values = mycols) +
  theme_void()+
  xlim(0.5, 2.5)



Version: Français





Comment ( 1 )

  • Niels

    Thanks! Very helpful. Your plots render beautifully, while mine are jagged (my non-polar plots are fine). Any idea why and how to fix?

Give a comment

Want to post an issue with R? If yes, please make sure you have read this: How to Include Reproducible R Script Examples in Datanovia Comments