如何使用 geom_text() 标记 geom_bar(position = 'fill')

bud*_*ong 2 r ggplot2 geom-bar geom-text

经过相当长的一段时间搜索后,我没有找到解决我的问题的例子:

如何使用 geom_text() 标记 geom_bar(position = 'fill')?

mydf = data.frame(
  'sample' = sample(x = LETTERS[1:3], size = 111,replace = T),
  'category' = sample(x = 1:11, size = 111,replace = T)
)


mydf %>% 
  group_by(sample) %>%
  ggplot( aes(fill=sample, x=category)) + 
  geom_bar( position="fill" )
 # Does not work: +  geom_text(position='fill', aes(label = ..y..))
Run Code Online (Sandbox Code Playgroud)

预期结果:在条形中间标记 %,如示例所示(除了它显示计数,与我的情况不同): 来自https://ggplot2.tidyverse.org/reference/geom_text.html

我想真正的问题是如果我使用 geom_bar(position = 'fill'),“y”和“label”是什么,

我对 ggplot 混合计算(每个类别的比例)与可视化感到困惑。

谢谢!

小智 7

创建一个新的数据框ggp来存储绘图数据

ggp <- mydf %>% count(sample,category)
Run Code Online (Sandbox Code Playgroud)

geom_bar使用数据框中的数据进行绘图-x=category, y=count(n), fill=sample

ggplot(ggp,aes(category,n,fill=sample)) +
geom_bar(stat="identity",position = "fill") + 
geom_text(aes(label=n),position = position_fill(vjust = 0.5))
Run Code Online (Sandbox Code Playgroud)