r - 使用 R / ggplot2 将标签添加到 geom_bar() 内的单个 %
问题描述
bgraph <- ggplot(data = data, aes(x = location)) +
geom_bar(aes(fill = success))
success
是一个百分比,计算为 4 个类别的因子,具有数据集的不同 4 个结果。我可以很容易地单独计算它们,但是由于ggplot
当前构成,它们是由geom_bar(aes(fill=success))
.
data <- as.data.frame(c(1,1,1,1,1,1,2,2,3,3,3,3,4,4,4,4,4,4,
4,4,5,5,5,5,6,6,6,6,6,6,7,7,7,7,7))
data[["success"]] <- c("a","b","c","c","d","d","a","b","b","b","c","d",
"a","b","b","b","c","c","c","d","a","b","c","d",
"a","b","c","c","d","d","a","b","b","c","d")
names(data) <- c("location","success")
bgraph <- ggplot(data = data, aes(x = location)) +
geom_bar(aes(fill = success))
bgraph
如何获得各个百分比的标签?更具体地说,我希望每个条形图有 4 个单独的百分比。一种分别代表黄色、浅橙色、橙色和红色。% 加起来等于 1。
解决方案
如何使用其中的相对频率创建一个摘要框架,location
然后将其与geom_col()
and一起使用geom_text()
?
# Create summary stats
tots <-
data %>%
group_by(location,success) %>%
summarise(
n = n()
) %>%
mutate(
rel = round(100*n/sum(n)),
)
# Plot
ggplot(data = tots, aes(x = location, y = n)) +
geom_col(aes(fill = fct_rev(success))) + # could only get it with this reversed
geom_text(aes(label = rel), position = position_stack(vjust = 0.5))
推荐阅读
- javascript - React setState - 异步更改元素类
- mysql - 将 DATE_ADD 与 NOW 合并在 MySQL 上不起作用
- docker - 如何增加 docker 镜像的大小?
- google-cloud-platform - 在终端命令中链接到谷歌云存储桶文件?
- amazon-web-services - K8s 动态卷预置:AWS 上的动态预置不支持 claim.Spec.Selector
- python - 在模块化 python 代码库中使用 Dask LocalCluster()
- java - 使用 Retrofit2 在 Recycleview 中得到空响应?
- algorithm - 如何计算 (31,26) 的汉明码?
- javascript - 如何在 node.js 中创建一个登录页面,该页面指向需要在客户端使用 p5.js 运行的网页?
- java - Appium问题。如果“listen eaddrinuse: address already in use”,如何停止呢?为什么它没有停止?