In this article we will learn how to create pie chart in R using ggplot2 package.
Theory
Are you familiar or new to creating reporting visualizations?
Often, the data is grouped by some factor to display such as month, season, product, and many more.
For the purposes of reporting, you will often be required to create pie charts that show the fraction of the total amount that belongs to each group.
Now, it’s time to create a pie chart in R!
Below I will show an example of the usage of a popular R visualization package ggplot2.
Application
Below are the steps we are going to take to make sure we do master the skill of creating pie chart in R:
- Installing ggplot2 package
- Loading the bookings.csv file into R
- Creating a pie chart in R
Part 1. Installing ggplot2 package
As R doesn’t have this command built in, we will need an additional package in order to create a time series plot in R.
You can learn more about ggplot2 package here.
In order to install and “call” the package into your workspace, you should use the following code:
install.packages("ggplot2")
library(ggplot2)
Part 2. Loading the training_names.csv file into R
For the purpose of this tutorial, I created a sample .csv dataset that you can use to practice creating a pie chart in R.
The file can be downloaded here: bookings.csv
Now, let’s go ahead and load it into R using the following command:
mydata<-read.csv("/Users/DataSharkie/Desktop/bookings.csv")
Note: remember that your location of the file will be different from mine, so adjust the code accordingly!
If you would like to learn more on how to import .csv files into R you can find an article here.
Once the dataset is imported, we can view the table using the following command:
View(mydata)
You will see two columns: "season" and "transactions".
Part 3. Creating a pie chart in R
Our goal here is to visualize the data in the two columns to show the relative volume of transactions by season compared to the total volume.
Now let's get into creating a pie chart in R!
Use the following code to arrive at our pie chart:
ggplot(bookings, aes(x = "", y = transactions, fill = season)) +
geom_bar(stat = "identity") +
coord_polar("y")
Not as visually appealing right?
But in R programming there is always a solution for us! Everything can be defined and framed the way we want it to look.
Now, let's add some more "design" to our pie chart and make it look presentable 🙂
ggplot(bookings, aes(x = "", y = transactions, fill = season)) +
geom_bar(stat = "identity", color = "white") +
coord_polar("y", start = 0)+
theme_void()
Much better right?
Although creating a pie chart is not a technically difficult task, it may take some time to discover all features that ggplot2 package includes.
If you are interested to learn more about importing different data formats into R, you can find more articles here.