且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用ggplot2创建带有百分比标签的饼图?

更新时间:2023-11-26 12:04:28

尝试以下操作:

library(dplyr)
library(ggplot2)
data <- data.frame(a=c("a1","a1","a2","a3","a1","a2","a3","a4","a2","a1","a5","a4","a3"),b=1:13)
data <- data %>% 
  group_by(a) %>% 
  count() %>% 
  ungroup() %>% 
  mutate(per=`n`/sum(`n`)) %>% 
  arrange(desc(a))
data$label <- scales::percent(data$per)
ggplot(data=data)+
  geom_bar(aes(x="", y=per, fill=a), stat="identity", width = 1)+
  coord_polar("y", start=0)+
  theme_void()+
  geom_text(aes(x=1, y = cumsum(per) - per/2, label=label))

我还提供了另一个版本的饼图,可以翻转饼图和标签的顺序(如果那是您的意思):

I include also another version of the pie chart, flipping the order of the pie slices and labels (if that is what you meant):

ggplot(data=data)+
  geom_bar(aes(x="", y=per, fill=a), stat="identity", width = 1)+
  coord_polar("y", start=0, direction = -1)+
  theme_void()+
  geom_text(aes(x=1, y = cumsum(per) - per/2, label=label))