在 R ggplot2 中使用 position = "fill" 在条形图上绘制标签

val*_*val 1 plot r bar-chart ggplot2

如何使用 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))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

但是,如果我尝试绘制填充条的计数,则它不起作用

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())
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

此外,如果我尝试:

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())
Run Code Online (Sandbox Code Playgroud)

我得到:

Error: stat_count() must not be used with a y aesthetic.
Run Code Online (Sandbox Code Playgroud)

小智 7

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

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))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明