There is no such thing as a geom_pie()
function that creates a pie chart in ggplot. Instead of that, one must use a “weird” strategy which consists in building first a single stacked bar plot from a dataframe, and then displaying it in a polar coordinate system. The stacked bar will thus be stretched to the point of becoming a pie. This reminds in a way of the strategy used when one wants to create a miniature planet from a panorama picture using the “little planet effect”.
Let’s take a simple example with this data set (blood type distribution in Norway, data retrieved here, original source: GiBlod.no). Here are the variables and the dataframe:
# variable 1
type <- c("O+", "A+", "B+", "AB+", "O-", "A-", "B-", "AB-")
# variable 2
proportion <- c(33.2, 41.6, 6.8, 3.4, 5.8, 7.4, 1.2, 0.6)
# dataframe
df <- data.frame(type, proportion)
In this example, we will decompose the procedure into four steps:
We use geom_col()
to draw the bar plot and map the variable with aes()
. Here, x=
is set but not named by the mean of ""
, while y =
is set to proportion
. Finally we use fill=
to attribute a specific color to each blood type:
ggplot(df, aes(x="", y=proportion, fill=type))+
geom_col()
Now we need to exchange the cartesian coordinate system in a polar coordinate system. In this way, the stacked bar will be stretched around a central point of focus. For that we add coord_polar("y")
to the code:
ggplot(df, aes(x="", y=proportion, fill=type))+
geom_col() +
coord_polar("y")
The circular axis around the chart has very little meaning; it may thus be taken away. One way to do it is to remove the whole theme, which means that the grey background disappears as well. To do so, we just add theme_void
:
ggplot(df, aes(x="", y=proportion, fill=type)) +
geom_col() +
coord_polar("y") +
theme_void()
To be honest, the set of colors which comes automatically in ggplot()
is not very appetizing. Let’s use scale_fill_viridis_d()
to exchange the 8 original colors against 8 colors from the palette viridis:
ggplot(df, aes(x="", y=proportion, fill=type))+
geom_col() +
coord_polar("y") +
theme_void() +
scale_fill_viridis_d()
In this section, you will learn how to set/modify all the necessary elements that make a plot complete and comprehensible. Such elements are: