ggplot2:如何将百分比标签添加到圆环图 [英] ggplot2: How to add percentage labels to a donut chart

查看:1515
本文介绍了ggplot2:如何将百分比标签添加到圆环图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

R我很新,所以原谅我。我正在尝试使用ggplot2制作甜甜圈图。
我已修改后
的代码


I am pretty new to R... so forgive me. I'm trying to make donut plots using ggplot2. I have modified the code of the post ggplot Donut chart but now I'm not able to add the percentage on the chart. This is my attempt:

library(ggplot2)

blank_theme <- theme_minimal()+
  theme(
    axis.title.x = element_blank(),
    axis.title.y = element_blank(),
    panel.border = element_blank(),
    panel.grid=element_blank(),
    axis.ticks = element_blank(),
    plot.title=element_text(size=14, face="bold")
  )



dat = data.frame(count=c(319, 442, 239), category=c("University", "High Scool", "Lower"))


dat$fraction = dat$count / sum(dat$count)

dat$ymax = cumsum(dat$fraction)
dat$ymin = c(0, head(dat$ymax, n=-1))

dat$category <- factor(dat$category, levels = c("University", "High Scool", "Lower"))


p1 = ggplot(dat, aes(fill=category, ymax=ymax, ymin=ymin, xmax=4, xmin=3)) +
  geom_rect(color='blue') +
  coord_polar(theta="y") +
  xlim(c(1, 4)) 



edu<-p1 + scale_fill_brewer("Education") + blank_theme +
  theme(axis.text.x=element_blank()) + theme(legend.position=c(.5, .5)) + ggtitle("") +
  theme(panel.grid=element_blank()) +
  theme(axis.text=element_blank()) +
  theme(axis.ticks=element_blank()) +
  theme(legend.title = element_text(size=16, face="bold")) +
  theme(legend.text = element_text(size = 14, face = "bold")) 

edu

I've tried many geom_text and scale_y_continuous code but... nothing. May someone help me? Thanks

解决方案

You could use geom_label:

edu +  geom_label(aes(label=paste(fraction*100,"%"),x=3.5,y=(ymin+ymax)/2),inherit.aes = TRUE, show.legend = FALSE)

这篇关于ggplot2:如何将百分比标签添加到圆环图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆