如何使用ggplot2创建包含百分比标签的饼图?
我有一个数据框,并希望在一个特定的列上创建一个饼图,指出此列中每个级别的百分比。如何使用ggplot2创建包含百分比标签的饼图?
data <- data.frame(a=c("a1","a1","a2","a3","a1","a2","a3","a4","a2","a1","a5","a4","a3"),
b=1:13)
换句话说,我希望有一个饼图,表明A1的产生比例,A2,...
此外,我需要在图表上显示的百分比。我怎样才能完成这一切只有ggplot2包?
任何小小的帮助将不胜感激!
尝试以下操作:
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(per)
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))
我还包括饼图的另一个版本,翻转圆形切片和标签的顺序(如果这是你的意思):
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))
,但是有错误,标签(百分数)没有完全出现在他们应该的区域上,标签a1在a2区域 – far
您没有意义,请检查我计算的频率表在你的数据集上。标签对应的相对频率:a1 = 4(0.308)... –
检查编辑,也许这就是你正在寻找的... –
您可以检查[这里](https://开头stackov erlot.com/questions/35682703/display-percentage-values-on-a-pie-chart) – akrun
我没有确切的值列,应该在geom_bar中使用aes(y = .. count ..)计算它,并且这个问题导致问题 – far