如何使用 geom_text() 标记 geom_bar(position = 'fill')
How to label geom_bar(position = 'fill') using geom_text()
在 SO 中搜索了很长一段时间后,我没有找到解决我问题的示例:
如何使用 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..))
预期结果:在条形中间标记 %,如示例所示(除了它显示计数,与我的情况不同):
来自 https://ggplot2.tidyverse.org/reference/geom_text.html
我想真正的问题是什么是 "y" 和 "label" 如果我使用 geom_bar(position = 'fill'),
我对 ggplot 混合计算(每个类别的比例)与可视化感到困惑。
谢谢!
创建一个新的数据框ggp
来存储绘图数据
ggp <- mydf %>% count(sample,category)
使用数据框中的数据绘制 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))
在 SO 中搜索了很长一段时间后,我没有找到解决我问题的示例:
如何使用 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..))
预期结果:在条形中间标记 %,如示例所示(除了它显示计数,与我的情况不同):
我想真正的问题是什么是 "y" 和 "label" 如果我使用 geom_bar(position = 'fill'),
我对 ggplot 混合计算(每个类别的比例)与可视化感到困惑。
谢谢!
创建一个新的数据框ggp
来存储绘图数据
ggp <- mydf %>% count(sample,category)
使用数据框中的数据绘制 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))