ggplot 将文本添加到 R 中圆环图的中心

J.S*_*ree 1 text r data-visualization ggplot2 donut-chart

我正在使用 ggplot2 处理圆环图,但我需要绘图的中心来包含文本。

这是示例数据(从该站点找到:https : //www.datanovia.com/en/blog/how-to-create-a-pie-chart-in-r-using-ggplot2/):

library(dplyr)
count.data <- data.frame(
  class = c("1st", "2nd", "3rd", "Crew"),
  n = c(325, 285, 706, 885),
  prop = c(14.8, 12.9, 32.1, 40.2)
)
count.data <- count.data %>%
  arrange(desc(class)) %>%
  mutate(lab.ypos = cumsum(prop) - 0.5*prop)
count.data
Run Code Online (Sandbox Code Playgroud)

然后我修改了他们的代码以获得这个甜甜圈图:

library(ggplot2)
library(dplyr)

mycols <- c("#0073C2FF", "#EFC000FF", "#868686FF", "#CD534CFF")

ggplot(count.data, aes(x = 2, y = prop, fill = class)) +
  geom_bar(stat = "identity", color = "white") +
  coord_polar(theta = "y", start = 0)+
  geom_text(aes(y = lab.ypos, label = paste0("n = ", n, ", \n", prop, "%")), color = "white")+
  scale_fill_manual(values = mycols) +
  theme_void() +
  xlim(.5, 2.5) 
Run Code Online (Sandbox Code Playgroud)

情节是这样的:

在此处输入图片说明

这正是我想要的,只是我需要甜甜圈的中心来获得来自变量的比例。在这种情况下,我希望中心说 40.2%(在这个例子中是船员的支柱)。

我该怎么做呢?

Max*_*lon 5

编辑

按照@aosmith 的建议使用注释,并直接呼叫工作人员。


像这样?

ggplot(count.data, aes(x = 2, y = prop, fill = class)) +
  geom_bar(stat = "identity", color = "white") +
  coord_polar(theta = "y", start = 0)+
  geom_text(aes(y = lab.ypos, label = paste0("n = ", n, ", \n", prop, "%")), color = "white")+
  scale_fill_manual(values = mycols) +
  theme_void() +
  xlim(.5, 2.5) +
  annotate(geom = 'text', x = 0.5, y = 0, label = paste0(count.data$prop[count.data$class == 'Crew'], "%"))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明