How to plot doughnut chart in R?
MACHINE LEARNING RECIPES DATA CLEANING PYTHON DATA MUNGING PANDAS CHEATSHEET     ALL TAGS

# How to plot doughnut chart in R?

This recipe helps you plot doughnut chart in R

0

## Recipe Objective

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: ​

1. geom_point() - for plotting points
2. geom_bar() - for plotting bar graph
3. geom_rect() - for plotting each group as a rectangle
4. geom_histogram() - for plotting histogram

The basic syntax of gggplot2 plots is: ​

ggplot(data, mapping = aes(x =, y=)) + geometric object ​

where: ​

1. data : Dataframe that is used to plot the chart
2. mapping = aes() : aesthetic mapping which deals with controlling axis (x and y indicates the different variables)
3. geometric object : Indicates the code for typeof plot you need to visualise.

This recipe demonstrates how to make a Donut Chart using ggplot2.

## STEP 1: Loading required library and dataset

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,...
```

## STEP 2: Plotting a Donut Chart using ggplot

We use geometric object as geom_rect() to plot each group as a rectangle and then converting it to a ring using coor_polar().

Note:

1. The + sign in the syntax earlier makes the code more readable and enables R to read further code without breaking it.
2. xlim() is used to convert pie to donut by adding an empty circle in the middle
3. We also use labs() function to give a title to the graph
``` # 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)") ```

#### Relevant Projects

##### Census Income Data Set Project - Predict Adult Census Income
Use the Adult Income dataset to predict whether income exceeds 50K yr based on census data.

##### Choosing the right Time Series Forecasting Methods
There are different time series forecasting methods to forecast stock price, demand etc. In this machine learning project, you will learn to determine which forecasting method to be used when and how to apply with time series forecasting example.

##### Predict Macro Economic Trends using Kaggle Financial Dataset
In this machine learning project, you will uncover the predictive value in an uncertain world by using various artificial intelligence, machine learning, advanced regression and feature transformation techniques.

##### Natural language processing Chatbot application using NLTK for text classification
In this NLP AI application, we build the core conversational engine for a chatbot. We use the popular NLTK text classification library to achieve this.

##### Machine Learning Project to Forecast Rossmann Store Sales
In this machine learning project you will work on creating a robust prediction model of Rossmann's daily sales using store, promotion, and competitor data.

##### PySpark Tutorial - Learn to use Apache Spark with Python
PySpark Project-Get a handle on using Python with Spark through this hands-on data processing spark python tutorial.

##### Ecommerce product reviews - Pairwise ranking and sentiment analysis
This project analyzes a dataset containing ecommerce product reviews. The goal is to use machine learning models to perform sentiment analysis on product reviews and rank them based on relevance. Reviews play a key role in product recommendation systems.

##### Topic modelling using Kmeans clustering to group customer reviews
In this Kmeans clustering machine learning project, you will perform topic modelling in order to group customer reviews based on recurring patterns.

##### Predict Credit Default | Give Me Some Credit Kaggle
In this data science project, you will predict borrowers chance of defaulting on credit loans by building a credit score prediction model.

##### Deep Learning with Keras in R to Predict Customer Churn
In this deep learning project, we will predict customer churn using Artificial Neural Networks and learn how to model an ANN in R with the keras deep learning package.