如何使用 R 的 ggplot2 编辑圆环图的标签?

How to edit the labels of the donut chart using ggplot2 of R?

我正在尝试使用以下代码创建圆环图 -

library (ggplot2)
data = data.frame (
 category = c("No/Minimal", "Mild", "Moderate", "Moderately Severe", "Severe"),
 count = c(27,21,179,67,32))

data$fraction = data$count/sum(data$count)
data$ymax = cumsum(data$fraction)
data$ymin = c(0, head(data$ymax, n=-1))

data$category = factor (data$category, levels = c("No/Minimal", "Mild", "Moderate", "Moderately Severe", "Severe"))

p = ggplot(data, aes(ymax=ymax, ymin=ymin, xmax=4, xmin=3, fill=category)) +
 geom_rect() +
 coord_polar(theta="y") +
 xlim(c(2, 4))
p

dep<-p + scale_fill_brewer("Depression Level") + theme_void() +
 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=14, face="bold")) +
 theme(legend.text = element_text(size = 12, face = "bold"))
dep
dep+geom_label(aes(label=paste(fraction*100,"%"),x=3.5,y=(ymin+ymax)/2),inherit.aes = TRUE, show.legend = FALSE)

它给了我这样的输出 -

但我想像这样显示百分比 9.8%、54.9%、20.5%、6.4% ...

我应该在此代码中添加或更改什么?

在您的 geom_label 中使用带有 3 位数字的 round 怎么样?

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

要加粗和变大,请更改 fontfacesize

geom_label(aes(label=paste(round(fraction, digits = 3)*100,"%"),x=3.5,y=(ymin+ymax)/2),inherit.aes = TRUE, show.legend = FALSE, 
               fontface = "bold", size = 5)

将最后一行的label改为:

paste0(formatC(100*fraction, digits=1, format="f"), "%")
dep + geom_label(aes(label=paste0(formatC(100*fraction, digits=1, format="f"), "%"),x=3.5,y=(ymin+ymax)/2),
               inherit.aes = TRUE, show.legend = FALSE)