如何使用ggplot2创建带有百分比标签的饼图? [英] How to create a pie chart with percentage labels using ggplot2?
本文介绍了如何使用ggplot2创建带有百分比标签的饼图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据框,想在一个特定的列上创建一个饼图,以指示该列中每个级别的百分比.
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)
换句话说,我想要一个饼图来指示a1,a2,...的出现百分比...
In other words, I want to have a pie chart that indicates the occurrence percentage of a1,a2,...
此外,我需要在图表上显示该百分比.我该如何仅使用ggplot2软件包来完成所有这些工作?
In addition, I need the percentage to be shown on the chart. How can I accomplish this all only with ggplot2 package?
任何帮助将不胜感激!
推荐答案
尝试以下操作:
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))
这篇关于如何使用ggplot2创建带有百分比标签的饼图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文