r - ggplot:条形顶部的百分比,但依靠 y-aes
问题描述
我正在尝试geom_bar
在 ggplot 中使用来制作一个图表,该图表具有计数y-aes
但在条形顶部的总组百分比。我的数据是cp.dat2
,“orsok”列有 9 个因子变量。
我试过了
library(ggplot2)
library(scales)
ggplot(cp.dat2, aes(x = as.factor(orsok))) +
geom_bar(aes(y = (..count..)/sum(..count..))) +
geom_text(aes(y = ((..count..)/sum(..count..)), label = scales::percent((..count..)/sum(..count..))), stat = "count", vjust = -0.25) +
scale_y_continuous(labels = percent)
我想要的是获得 y-aes 的计数,但将百分比保持在所有条形的顶部..
另外,我可以改变酒吧吗?例如,将 9.16% 的条放在前面(2.29% 的条在此)。
任何人都可以帮忙吗?
解决方案
您可以使用 订购酒吧forcats::infreq()
。您可以轻松地使用 y 位置的计数。这是自动完成的geom_bar()
,而您必须使用 访问文本的计算统计信息after_stat()
。请注意,它after_stat()
取代了旧的..stat..
符号并且更加灵活。
library(ggplot2)
library(scales)
cp.dat2 <- data.frame(
orsok = sample(41:51, 100, replace = TRUE)
)
ggplot(cp.dat2, aes(x = forcats::fct_infreq(factor(orsok)))) +
geom_bar() +
geom_text(
stat = "count",
aes(y = after_stat(count),
label = after_stat(percent(count / sum(count)))),
vjust = -0.25
)
由reprex 包于 2021-04-20 创建(v1.0.0)
推荐阅读
- c - 尝试在文件流中指示 EOF 时,Enter 和 Ctrl+D 之间的关系是什么?
- c++ - 关于将指向 char 的指针转换为另一种类型指针的问题
- azure - Azure 函数应用 - Microsoft.WindowsAzure.Storage:发现重复设置“帐户名”
- python - Discord.py 重写。如何创建添加角色的命令?
- ios - 在 Tableview 中偏移 HeaderView 以显示类似卡片
- r - 将日期格式从 dd-mm-yyyy 转换为 dd/mm/yyyy
- html - 如何使两个不同表格中的两个形状重叠
- gatsby - Gatsby 中的到达路由器链接闪烁页面然后消失
- php - 从用户名roblox php获取用户ID
- tensorflow - 使用 Tensorflow Saved Format .pb 保存优化器状态