我正在使用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
然后我修改了他们的代码以获取此甜甜圈图:
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)
情节看起来像这样:
这正是我想要的,除了我需要甜甜圈的中心以具有来自变量的比例。在这种情况下,我希望中心说40.2%(在此示例中为乘员组)。
我该怎么做?