我想在条形图上为每个齿轮添加百分比标签,但保持计数y刻度。例如。所有“齿轮3”的10%为“ 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或整洁。我找到了一些解决方案,但是我的原始数据又遇到了其他问题。
EDIT:建议与以下内容重复: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)
我撤回了结束投票,这确实不是重复的to this thread。问题是ggplot不知道每个构面都是一组。 I found this very useful tutorial提供了一个不错的解决方案。只需添加aes(group = 1)
library(ggplot2)
library(scales)
ds <- mtcars
ds$gear <- as.factor(ds$gear)
ggplot(ds, aes(gear, fill = gear)) +
geom_bar(aes(fill = factor(..x..)), stat="count") +
facet_grid(cols = vars(cyl), margins = T) +
geom_text(aes( label = scales::percent(..prop..), group = 1), stat= "count")
由reprex package(v0.3.0)在2020-02-07创建