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

时间:2017-08-13 07:04:01

标签: r ggplot2 pie-chart

我有一个数据框,想要在一个特定列上创建一个饼图,表示此列中每个级别的百分比。

   data <- data.frame(a=c("a1","a1","a2","a3","a1","a2","a3","a4","a2","a1","a5","a4","a3"),
                   b=1:13)

换句话说,我想要一个饼图,表明a1,a2,...的出现百分比。

另外,我需要在图表上显示百分比。我怎样才能用ggplot2包完成这一切?

非常感谢任何一点帮助!

1 个答案:

答案 0 :(得分:6)

尝试以下方法:

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

enter image description here

我还包含饼图的另一个版本,翻转饼图切片和标签的顺序(如果这是你的意思):

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

enter image description here