gpt4 book ai didi

r - 在 R ggplot2 中位置 = "fill"的条形图上绘制标签

转载 作者:行者123 更新时间:2023-12-05 08:56:27 25 4
gpt4 key购买 nike

one 如何使用 ggplot2 绘制带有计数标签的“填充”条形图?

我可以为“堆叠”栏执行此操作。但除此之外我很困惑。

这是一个使用 dplyrmpg 数据集的可重现示例

library(ggplot)
library(dplyr)

mpg_summ <- mpg %>%
group_by(class, drv) %>%
summarise(freq = n()) %>%
ungroup() %>%
mutate(total = sum(freq),
prop = freq/total)

g <- ggplot(mpg_summ, aes(x = class, y = prop, group = drv))
g + geom_col(aes(fill = drv)) +
geom_text(aes(label = freq), position = position_stack(vjust = .5))

enter image description here

但是如果我尝试绘制实心条的计数,它就不起作用

g <- ggplot(mpg_summ, aes(x=class, fill=drv))
g + stat_count(aes(y = (..count..)/sum(..count..)), geom="bar", position="fill") +
scale_y_continuous(labels = percent_format())

enter image description here

此外,如果我尝试:

g <- ggplot(mpg_summ, aes(x=class, fill=drv))
g + geom_bar(aes(y = freq), position="fill") +
geom_text(aes(label = freq), position = "fill") +
scale_y_continuous(labels = percent_format())

我得到:

Error: stat_count() must not be used with a y aesthetic.

最佳答案

我错过了上一题的填充部分。这应该让你到达那里:

library(ggplot2)
library(dplyr)

mpg_summ <- mpg %>%
group_by(class, drv) %>%
summarise(freq = n()) %>%
ungroup() %>%
mutate(total = sum(freq),
prop = freq/total)

g <- ggplot(mpg_summ, aes(x = class, y = prop, group = drv))
g + geom_col(aes(fill = drv), position = 'fill') +
geom_text(aes(label = freq), position = position_fill(vjust = .5))

enter image description here

关于r - 在 R ggplot2 中位置 = "fill"的条形图上绘制标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40622017/

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