Search code examples
rggplot2donut-chart

Modify position and format of percentage labels of donut chart in ggplot2


I have plotted a donut chart with the code below:

library(tidyverse)
library(ggthemes)

df <- data.frame(flavor = c("Chocolate", "Strawberry", "Pistachio"),
                        per_sold = c(.20, .30, .50))
df %>%
  ggplot(aes(x = 2, y = per_sold, fill = flavor)) +
  geom_bar(stat = "identity") +
  xlim(0.5, 2.5) +
  coord_polar(start = 0, theta = "y") +
  xlab("") +
  ylab("") +
  theme(axis.ticks = element_blank(),
        axis.text = element_blank(),
        axis.title = element_blank(),
        panel.grid = element_blank(),
        panel.border = element_blank(),
        legend.title = element_text(size = rel(2)),
        legend.text=element_text(size=rel(1.5))) +
  geom_text(aes(label = per_sold), size = 6)

Out:

enter image description here

As you can see, the position of labels are not correct, also I want it show the format of % instead of float number with digit.

How could I modify the code to achive this? Thanks.


Solution

  • All you need is position_stack(vjust = 0.5) and scales::percent:

    library(scales)
    df %>%
      ggplot(aes(x = 2, y = per_sold, fill = flavor)) +
      geom_bar(stat = "identity") +
      xlim(0.5, 2.5) +
      coord_polar(start = 0, theta = "y") +
      xlab("") +
      ylab("") +
      theme(axis.ticks = element_blank(),
            axis.text = element_blank(),
            axis.title = element_blank(),
            panel.grid = element_blank(),
            panel.border = element_blank(),
            legend.title = element_text(size = rel(2)),
            legend.text=element_text(size=rel(1.5))) +
      geom_text(aes(label = scales::percent(per_sold)),
                size = 6, position = position_stack(vjust = 0.5))
    

    enter image description here