A pie chart is a circle divided into sectors that
each represent a proportion of the whole. This page explains how to
build one with the ggplot2
package.
ggplot2
does not offer any specific geom to build
piecharts. The trick is the following:
group
here) and its value (value
here)geom_bar()
function.coord_polar()
The result is far from optimal yet, keep reading for improvements.
Previous version looks pretty bad. We need to:
It’s better now, just need to add labels directly on chart.
# Load ggplot2
library(ggplot2)
# Create Data
data <- data.frame(
group=LETTERS[1:5],
value=c(13,7,9,21,2)
)
# Basic piechart
ggplot(data, aes(x="", y=value, fill=group)) +
geom_bar(stat="identity", width=1, color="white") +
coord_polar("y", start=0) +
theme_void() # remove background, grid, numeric labels
geom_text()
Since ggplot2 v2.2.0, the position of labels can easily be set with
position_stack()
.
# Load ggplot2
library(ggplot2)
# Create Data
data <- data.frame(
group=LETTERS[1:5],
value=c(13,7,9,21,2)
)
# Basic piechart
ggplot(data, aes(x="", y=value, fill=group)) +
geom_bar(stat="identity", width=1, color="white") +
coord_polar("y", start=0) +
theme_void() + # remove background, grid, numeric labels
geom_text(aes(label = group), position = position_stack(vjust = 0.5)) +
scale_fill_brewer(palette="Set1")
👋 After crafting hundreds of R charts over 12 years, I've distilled my top 10 tips and tricks. Receive them via email! One insight per day for the next 10 days! 🔥