How to create a pie chart with percentage labels using ggplot2? [closed]

痞子三分冷 提交于 2019-12-06 15:14:52

问题


I have a data frame and want to create a pie chart on one specific column that indicates the percentage of each level in this column.

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

In other words, I want to have a pie chart that indicates the occurrence percentage of a1,a2,...

In addition, I need the percentage to be shown on the chart. How can I accomplish this all only with ggplot2 package?

Any little help would be greatly appreciated!


回答1:


Try the following:

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



来源:https://stackoverflow.com/questions/45657990/how-to-create-a-pie-chart-with-percentage-labels-using-ggplot2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!