简体   繁体   中英

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:

在此处输入图像描述

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.

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))

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM