R Pie Charts
A pie chart shows how a whole is divided into parts. Each slice's angle is proportional to its value. In R you draw one with pie():
budget <- c(Rent = 1200, Food = 450, Transport = 180, Fun = 250, Savings = 400)
pie(budget, main = "Monthly budget")
round(100 * budget / sum(budget), 1) Rent Food Transport Fun Savings
48.4 18.1 7.3 10.1 16.1
The names of the vector become slice labels. R draws slices counter-clockwise, starting at 3 o'clock.
Labels with percentages
Readers struggle to compare angles, so it helps to print the share on each slice:
budget <- c(Rent = 1200, Food = 450, Transport = 180, Fun = 250, Savings = 400)
pct <- round(100 * budget / sum(budget))
labels <- paste0(names(budget), " (", pct, "%)")
pie(budget, labels = labels, main = "Monthly budget")
labels[1] "Rent (48%)" "Food (18%)" "Transport (7%)" "Fun (10%)"
[5] "Savings (16%)"
Colours, start angle and direction
browsers <- c(Chrome = 64, Safari = 19, Edge = 5, Firefox = 3, Other = 9)
pie(browsers,
col = c("#4285f4", "#a3aaae", "#0078d7", "#ff7139", "#dddddd"),
clockwise = TRUE, # start at 12 o'clock and go clockwise
border = "white",
main = "Browser share (%)")
sum(browsers)[1] 100
clockwise = TRUE is how most people expect a pie to read. You can also use init.angle to rotate the first slice.
Adding a legend
With many slices, a legend can replace crowded labels:
langs <- c(Python = 38, R = 22, SQL = 25, Julia = 5, Other = 10)
cols <- hcl.colors(length(langs), "Set 2")
pie(langs, labels = NA, col = cols, main = "Languages used in a data team")
legend("right", legend = names(langs), fill = cols, cex = 0.9, bty = "n")
langs[order(-langs)]Python SQL R Other Julia
38 25 22 10 5
hcl.colors() returns a ready-made palette; "Set 2", "Dark 3" and "Viridis" are a few of the options (see hcl.pals()).
Pie charts from raw data
If your data is a list of categories, count them first with table():
orders <- c("tea", "coffee", "coffee", "juice", "coffee", "tea", "water", "coffee")
counts <- table(orders)
counts
pie(counts, main = "Drinks ordered")orders
coffee juice tea water
4 1 2 1
When to avoid a pie chart
Pie charts work best with few slices (2–5) that add up to a meaningful whole. When slices are similar in size, or when you want to compare categories across groups, a bar chart is easier to read. R's own help page for pie() recommends bar or dot charts for exactly this reason.
Test yourself
Which function draws a pie chart in base R?
- piechart()
- pie()
- circle()
- plot(type = "pie")
Where does R start drawing slices by default?
- 12 o'clock, clockwise
- 3 o'clock, counter-clockwise
- 6 o'clock, clockwise
- At random
How do you turn a vector of category names into slice sizes?
- sum()
- table()
- levels()
- cut()