gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 16:11:41 26 4
gpt4 key购买 nike

我正在使用 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)

剧情是这样的:

enter image description here

这正是我想要的,除了我需要 donut 的中心具有来自变量的比例。在这种情况下,我希望中心说出 40.2%(在本例中为 crew 的 Prop )。

我该怎么做?

最佳答案

编辑

按照@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'], "%"))

enter image description here

关于r - ggplot 将文本添加到 R 中圆环图的中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56546969/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com