J.Sabree
J.Sabree

Reputation: 2536

ggplot add text to the center of a donut chart in R

I am working on a donut chart using ggplot2, but I need the center of the plot to contain text.

Here's sample data (found from this site: https://www.datanovia.com/en/blog/how-to-create-a-pie-chart-in-r-using-ggplot2/):

library(dplyr)
count.data <- data.frame(
  class = c("1st", "2nd", "3rd", "Crew"),
  n = c(325, 285, 706, 885),
  prop = c(14.8, 12.9, 32.1, 40.2)
)
count.data <- count.data %>%
  arrange(desc(class)) %>%
  mutate(lab.ypos = cumsum(prop) - 0.5*prop)
count.data

I then modified their code to get this donut chart:

library(ggplot2)
library(dplyr)

mycols <- c("#0073C2FF", "#EFC000FF", "#868686FF", "#CD534CFF")

ggplot(count.data, aes(x = 2, y = prop, fill = class)) +
  geom_bar(stat = "identity", color = "white") +
  coord_polar(theta = "y", start = 0)+
  geom_text(aes(y = lab.ypos, label = paste0("n = ", n, ", \n", prop, "%")), color = "white")+
  scale_fill_manual(values = mycols) +
  theme_void() +
  xlim(.5, 2.5) 

The plot looks like this:

enter image description here

It is exactly what I want except I need the center of the donut to have the proportion from a variable. In this case, I want the center to say 40.2% (the prop of crew, in this example).

How do I do this?

Upvotes: 2

Views: 4559

Answers (1)

Max Teflon
Max Teflon

Reputation: 1800

Edit

Used annotate as suggested by @aosmith and made it a direct call to crew.


like this?

ggplot(count.data, aes(x = 2, y = prop, fill = class)) +
  geom_bar(stat = "identity", color = "white") +
  coord_polar(theta = "y", start = 0)+
  geom_text(aes(y = lab.ypos, label = paste0("n = ", n, ", \n", prop, "%")), color = "white")+
  scale_fill_manual(values = mycols) +
  theme_void() +
  xlim(.5, 2.5) +
  annotate(geom = 'text', x = 0.5, y = 0, label = paste0(count.data$prop[count.data$class == 'Crew'], "%"))

enter image description here

Upvotes: 7

Related Questions