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.
# 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) +
coord_polar("y", start=0)
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()
The tricky part is to compute the y position of labels using this
weird coord_polar
transformation.
# Load ggplot2
library(ggplot2)
library(dplyr)
# Create Data
data <- data.frame(
group=LETTERS[1:5],
value=c(13,7,9,21,2)
)
# Compute the position of labels
data <- data %>%
arrange(desc(group)) %>%
mutate(prop = value / sum(data$value) *100) %>%
mutate(ypos = cumsum(prop)- 0.5*prop )
# Basic piechart
ggplot(data, aes(x="", y=prop, fill=group)) +
geom_bar(stat="identity", width=1, color="white") +
coord_polar("y", start=0) +
theme_void() +
theme(legend.position="none") +
geom_text(aes(y = ypos, label = group), color = "white", size=6) +
scale_fill_brewer(palette="Set1")