How to create a pie chart using plotly in R?

This recipe helps you create a pie chart using plotly in R

Recipe Objective

A pie-chart is pictorial representation of categorical variable and it's numerical constituent in the form of a circle. The circle is divided into sectors that indicates a certain proportion of the whole. We prefer to use pie chart when there are less than 5 categories that needs to be compared. ​

In this recipe we are going to use Plotly package to plot the required pie-chart. Plotly package provides an interface to the plotly javascript library allowing us to create interactive web-based graphics entrirely in R. Plots created by plotly works in multiple format such as: ​

  1. R Markdown Documents
  2. Shiny apps - deploying on the web
  3. Windows viewer

Plotly has been actively developed and supported by it's community. ​

This recipe demonstrates how to plot a pie-chart in R using plotly package. ​

STEP 1: Loading required library and dataset

We will use an example of Expenses made by a student

# Data manipulation package library(tidyverse) # plotly package for data visualisation install.packages("plotly") library(plotly) # Type of expense type_of_expense = c('Rent', 'Grocery', 'Transport') # Amount Amount_USD = c(7000, 3500, 900) #creating a dataframe df = data.frame(type_of_expense,Amount_USD)

Observations: 200
Variables: 3
$ Age                     19, 21, 20, 23, 31, 22, 35, 23, 64, 30, 67, 35…
$ Annual.Income..k..      15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 19, 19…
$ Spending.Score..1.100.  39, 81, 6, 77, 40, 76, 6, 94, 3, 72, 14, 99, 1…

STEP 2: Plotting a pie chart using Plotly

We use the plot_ly() function to plot a pie chart.

Syntax: plot_ly( data = , labels = , values = , type = "pie", textinfo = "label+percent", insidetextorientation = "radial" )

Where:

  1. data = dataframe to be used
  2. labels = unique names of the categorical variable
  3. values = Corresponding values of the categories
  4. type = type of chart (in our case "pie")
  5. textinfo = information to be appeared on the section as labels
  6. insidetextorientation = indicates the alignment of the text

Note:

  1. The %>% sign in the syntax earlier makes the code more readable and enables R to read further code without breaking it.
  2. We also use layout() function to give a title to the graph

fig <- plot_ly(data = df, labels = ~type_of_expense, values = ~Amount_USD, type = "pie", textinfo = "label+percent", insidetextorientation = "radial") %>% layout(title = 'Pie Chart using Plotly') embed_notebook(fig)

What Users are saying..

profile image

Ed Godalle

Director Data Analytics at EY / EY Tech
linkedin profile url

I am the Director of Data Analytics with over 10+ years of IT experience. I have a background in SQL, Python, and Big Data working with Accenture, IBM, and Infosys. I am looking to enhance my skills... Read More

Relevant Projects

Deep Learning Project- Real-Time Fruit Detection using YOLOv4
In this deep learning project, you will learn to build an accurate, fast, and reliable real-time fruit detection system using the YOLOv4 object detection model for robotic harvesting platforms.

Build a Multi Touch Attribution Machine Learning Model in Python
Identifying the ROI on marketing campaigns is an essential KPI for any business. In this ML project, you will learn to build a Multi Touch Attribution Model in Python to identify the ROI of various marketing efforts and their impact on conversions or sales..

Azure Deep Learning-Deploy RNN CNN models for TimeSeries
In this Azure MLOps Project, you will learn to perform docker-based deployment of RNN and CNN Models for Time Series Forecasting on Azure Cloud.

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.

Abstractive Text Summarization using Transformers-BART Model
Deep Learning Project to implement an Abstractive Text Summarizer using Google's Transformers-BART Model to generate news article headlines.

Predict Churn for a Telecom company using Logistic Regression
Machine Learning Project in R- Predict the customer churn of telecom sector and find out the key drivers that lead to churn. Learn how the logistic regression model using R can be used to identify the customer churn in telecom dataset.

Learn to Build an End-to-End Machine Learning Pipeline - Part 2
In this Machine Learning Project, you will learn how to build an end-to-end machine learning pipeline for predicting truck delays, incorporating Hopsworks' feature store and Weights and Biases for model experimentation.

Many-to-One LSTM for Sentiment Analysis and Text Generation
In this LSTM Project , you will build develop a sentiment detection model using many-to-one LSTMs for accurate prediction of sentiment labels in airline text reviews. Additionally, we will also train many-to-one LSTMs on 'Alice's Adventures in Wonderland' to generate contextually relevant text.

Time Series Python Project using Greykite and Neural Prophet
In this time series project, you will forecast Walmart sales over time using the powerful, fast, and flexible time series forecasting library Greykite that helps automate time series problems.

Build an AI Chatbot from Scratch using Keras Sequential Model
In this NLP Project, you will learn how to build an AI Chatbot from Scratch using Keras Sequential Model.