How to Make a Pie Chart in R

Pie chart in R tutorial

A pie chart is a circular chart that is divided into slices to represent the portions of a whole. This tutorial explains how to create a pie chart in R using the package ggplot2.

Creating a Pie Chart in R

To create a pie chart in R, we can either use Base R or download a package like ggplot2.

Using Base R

To create a pie chart in base R, we can create some fake data and use the pie() function to create  a basic pie chart:

#create some fake data
amounts <- c(10, 11, 13, 22, 44)
categories <- c('A', 'B', 'C', 'D', 'E')

#make a pie chart using the data above
pie(amounts, labels = categories, main='Pie Chart')

This generates the following pie chart:

In order to add annotated percentages to the chart, we can use the following code:

amounts <- c(10, 11, 13, 22, 44) #create five different amounts
categories <- c('A', 'B', 'C', 'D', 'E') #create five category names
percents <- round(amounts/sum(amounts)*100) #determine % of whole for each amount
categories <- paste(categories, percents) #add percents to the labels 
categories <- paste(categories,'%',sep='') #add the "%" sign to the labels
pie(amounts,labels = categories, main="Pie Chart") #create chart w/ annotated labels

This generates the following pie chart with percentage labels:

Using ggplot2

We can also use the package ggplot2 to create a pie chart.

We’ll use the same fake dataset that we made above to create the pie chart.

#create some fake data
data <- data.frame("category" = c('A', 'B', 'C', 'D', 'E'),
                   "amount" = c(10, 11, 13, 22, 44))
data
# category amount
#1   A      10
#2   B      11
#3   C      13
#4   D      22
#5   E      44

Then we’ll create the actual pie chart:

#create some fake data
data <- data.frame("category" = c('A', 'B', 'C', 'D', 'E'),
                   "amount" = c(10, 11, 13, 22, 44))
#load ggplot2
library(ggplot2)

#create pie chart
ggplot(data, aes(x="", y=amount, fill=category)) +
geom_bar(stat="identity", width=1) +
coord_polar("y", start=0) +
geom_text(aes(label = paste0(amount, "%")), position = position_stack(vjust = 0.5)) +
labs(x = NULL, y = NULL, fill = NULL, title = "Pie Chart")

This generates the following chart:

Leave a Reply

Your email address will not be published. Required fields are marked *