ggplot2: 如何在环形图中添加百分比标签

7

我对R还很陌生,所以请原谅。我正在尝试使用ggplot2制作甜甜圈图。 我修改了ggplot Donut chart的代码,但现在我无法在图表上添加百分比。 这是我的尝试:

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

我尝试了很多geom_text和scale_y_continuous的代码,但是......什么都没发生。 有人可以帮帮我吗? 谢谢

1个回答

12

您可以使用geom_label

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

这里输入图片描述


...并且使标签变大...我尝试了"label.size",但它不起作用... - Giorjet
geom_label 中添加 size=8 或更大的字体大小(但不要放在 aes 内部)。 - scoa
我喜欢这个图表。有人知道怎样选择自己的颜色而不是蓝色的渐变吗? - Jacob Curtis
@user3281413 添加 + scale_fill_discrete() 并查看其帮助以选择颜色。 - scoa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接