A donut chart is a special type of pie-chart which consists of a ring instead of a circle. The ring is divided into sectors that indicates a certain proportion of the whole. We prefer to use donut chart over pie-chart as it is visually more appealing.
In this recipe we are going to use ggplot2 package to plot the required Donut Chart. ggplot2 package is based on the book "Grammar of Graphics" by Wilkinson. This package provides flexibility while incorporating different themes and plot specification with a high level of abstraction. The package mainly uses aesthetic mapping and geometric objects as arguments. Different types of geometric objects include:
The basic syntax of gggplot2 plots is:
ggplot(data, mapping = aes(x =, y=)) + geometric object
This recipe demonstrates how to make a Donut Chart using ggplot2.
Dataset description: It is the basic data about the customers going to the supermarket mall. The variable that we interested in is Annual.Income which is in 1000s and Spending Score
# Data manipulation package library(tidyverse) # ggplot for data visualisation library(ggplot2) # reading a dataset customer_seg = read.csv('Mall_Customers.csv') glimpse(customer_seg)
Rows: 200 Columns: 5 $ CustomerID
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1... $ Gender Male, Male, Female, Female, Female, Female, ... $ Age 19, 21, 20, 23, 31, 22, 35, 23, 64, 30, 67, ... $ Annual.Income..k.. 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 19, ... $ Spending.Score..1.100. 39, 81, 6, 77, 40, 76, 6, 94, 3, 72, 14, 99,...
We use geometric object as geom_rect() to plot each group as a rectangle and then converting it to a ring using coor_polar().
# Calculating percentages column df$fraction = df$Amount_USD / sum(df$Amount_USD) # Calculating cumulative percentages (top of each rectangle) column df$y_max = cumsum(df$fraction) # Calculating the bottom of each rectangle df$y_min = c(0, head(df$y_max, n=-1)) ggplot(df, aes(ymax=y_max, ymin=y_min, xmax=4, xmin=3, fill=type_of_expense)) + geom_rect() + # converting to polar coordinates (stacked rectangle to pie-chart) coord_polar(theta="y") + # Pie-chart to a ring xlim(c(2, 4)) + # to delete the unnecessary backround theme_void() + labs(title = "Expenses of student A (Donut Chart)")