【发布时间】:2020-02-07 14:27:01
【问题描述】:
我想为条形图添加每个齿轮的百分比标签,但保留计数 y 比例。 例如。 10% 的“3 档”是“4 缸”
library(ggplot)
ds <- mtcars
ds$gear <- as.factor(ds$gear)
p1 <- ggplot(ds, aes(gear, fill=gear)) +
geom_bar() +
facet_grid(cols = vars(cyl), margins=T)
p1
理想情况下仅在 ggplot 中,不添加 dplyr 或 tidy。我找到了其中一些解决方案,但随后我的原始数据出现了其他问题。
编辑:建议这是重复的: enter link description here
我之前也看到了这个,但无法将该代码集成到我想要的代码中:
# i just copy paste some of the code bits and try to reconstruct what I had earlier
ggplot(ds, aes(gear, fill=gear)) +
facet_grid(cols = vars(cyl), margins=T) +
# ..prop.. meaning %, but i want to keep the y-axis as count
geom_bar(aes(y = ..prop.., fill = factor(..x..)), stat="count") +
# not sure why, but I only get 100%
geom_text(aes( label = scales::percent(..prop..),
y= ..prop.. ), stat= "count", vjust = -.5)
【问题讨论】:
标签: ggplot2 count label bar-chart percentage