Pie and Donut Charts
Learn how to build a pie chart and a donut chart in ggplot2.
Getting started with pie charts in ggplot2
A circular statistical graph with sections that show numerical proportion is known as a pie chart. The arc length of each slice in the pie chart is equivalent to the count or proportion of that slice.
Pie charts are useful for quickly comparing different categories of a variable in relation to the whole. However, pie charts are a better choice when used to represent a variable with just a few categories, whereas bar charts are generally considered a better option for comparing several categories at once.
For example, we have the following dataset:
Shop sales dataset
Shop | Food | Units Sold |
A | Mexican | 25 |
B | Italian | 40 |
C | German | 15 |
D | Mediterranean | 20 |
Let’s create a data frame using the above dataset:
data <- data.frame("shop" = c('A', 'B', 'C', 'D'),"cuisine"=c('Mexican','Italian','German','Mediterranean'),"sales" = c(25, 40, 15, 20))
- Line 1: We use the
data.frame()
function to create a new data frame nameddata
, with the first column namedshop
, and thec()
function to create its entries. - Line 2: We add another column named
cuisine
with cuisine offered by the different shops. - Line 3: We create a third column named
sales
, which indicates the number of units sold, i.e., the sales data for each shop.
Now, we’ll use the head()
function to take a look at our newly created data frame:
head(data)
Next, we’ll use this data to build a pie chart. There is no specific geometric function in ggplot2
for creating a pie chart, so we’ll use the geom_bar()
function, which is used to build bar charts. We’ll then add the polar coordinate function to make the graph circular.
For building a pie chart, we can use either the geom_bar()
or the geom_col()
...