17 Pie charts
17.1 Description
“In general, pie charts work well when the goal is to emphasize simple fractions, such as one-half, one-third, or one-quarter.”
“They also work well when we have very small datasets.” - Claus O. Wilke, Fundamentals of Data Visualization (2019)
Pie-charts are ideal for comparing the proportions of categorical variable values, and we can build pie-charts using the ggpubr
package.
17.2 Set up
PACKAGES:
Install packages.
show/hide
install.packages("ggpubr")
library(ggpubr)
install.packages("ggplot2movies")
library(ggplot2movies)
library(ggplot2)
DATA:
Remove the missing values and "NC-17"
from mpaa
and summarise the count and percent.
show/hide
<- ggplot2movies::movies |>
movie_pie filter(mpaa != "" & mpaa != "NC-17") |>
group_by(mpaa) |>
summarise(cnt = n()) |>
mutate(
perc = round(cnt / sum(cnt), 3),
mpaa = factor(mpaa,
levels = c("PG", "PG-13", "R")))
glimpse(movie_pie)
#> Rows: 3
#> Columns: 3
#> $ mpaa <fct> PG, PG-13, R
#> $ cnt <int> 528, 1003, 3377
#> $ perc <dbl> 0.108, 0.204, 0.688
17.3 Grammar
CODE:
Create labels with
labs()
Initialize the graph with
ggplot()
and providedata
Assign
"perc"
tox
Assign
labs
tolabel
Assign
"in"
tolab.pos
Assign
"white"
tolab.font
andcolor
Assign
"mpaa"
tofill
Remove legend with
theme(legend.position = "none")
show/hide
<- paste0(movie_pie$mpaa, " (",
labs 100*movie_pie$perc), "%)")
(<- labs(
labs_pie title = "Percent MPAA ratings for IMDB movies",
x = "Percent MPAA rating")
<- ggpubr::ggpie(movie_pie,
ggp2_pie x = "perc", label = labs,
lab.pos = "in", lab.font = "#ffffff",
fill = "mpaa", color = "#ffffff") +
theme(legend.position = "none")
+
ggp2_pie labs_pie
GRAPH: