gpt4 book ai didi

r - R语言包 `ggmosaic`中,如何给列添加重量百分比标签

转载 作者:行者123 更新时间:2023-12-05 05:29:42 26 4
gpt4 key购买 nike

ggmosaic包中,如何给列添加重量百分比标签?我想添加每列的百分比值(每列总百分比等于 100%)。谢谢!

library(tidyverse)
library(ggmosaic)

ggplot(data = titanic) +
geom_mosaic(aes(x = product(Class), fill = Survived)) +
geom_mosaic_text(size=5,aes(x = product(Class), fill = Survived))

最佳答案

您可以使用 ggplot_build 计算每个总计数值中每个类别的百分比,如下所示:

library(tidyverse)
library(ggmosaic)

p <- ggplot(data = titanic) +
geom_mosaic(aes(x = product(Class), fill = Survived)) +
geom_mosaic_text(size=5,aes(x = product(Class), fill = Survived))

p + geom_text(data = ggplot_build(p)$data[[1]] %>%
group_by(x__Class) %>%
mutate(pct = .wt/sum(.wt)*100),
aes(x = (xmin+xmax)/2, y = (ymin+ymax)/2, label=round(pct, 2)))

创建于 2022-12-22 reprex v2.0.2

关于r - R语言包 `ggmosaic`中,如何给列添加重量百分比标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74887132/

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