r - 如何使用ggplot geom_bar在堆积列中显示百分比?
问题描述
我正在尝试在堆积条形图中添加百分比标签。我可以添加什么到我的 geom_bar 以显示堆叠条内的百分比标签?
这是我的数据:
myresults=data.frame(
manipulation=rep(c(-20,-10,0,10,20,-20,-10,0,10,20,-20,-10,0,10,20)),
variable=rep(c("a","a","a","a","a","f","f","f","f","f","l","l","l","l","l")),
value=c(73,83,76,75,78,261,301,344,451,599,866,816,780,674,523))
我对此知之甚少。我搜索了“gglot 堆积条百分比标签”,发现可以使用“+ geom_text(stat="count")”添加百分比标签。
但是当我将 + geom_text(stat="count") 添加到我的 ggplot geom_bar 时,R 说“错误:stat_count() 不能与任何美学一起使用。” 我试图弄清楚什么是审美,但它并不是很成功。
这就是我所做的:
mydata <- ggplot(myresults, aes(x=manipulation, y=value, fill=variable))
mydata + geom_bar(stat="identity", position="fill", colour="black") + scale_fill_grey() + scale_y_continuous(labels=scales::percent) + theme_bw(base_family="Cambria") + labs(x="Manipulation", y=NULL, fill="Result") + theme(legend.direction="vertical", legend.position="right")
解决方案
您可以执行类似于以下已接受答案的操作: 在 ggplot2 中向条形图添加百分比标签。主要区别在于您的值是堆积的(“堆叠”),而在该示例中它是并排的(“躲避”)
制作一列百分比:
myresults_pct <- myresults %>%
group_by(manipulation) %>%
mutate(pct=prop.table(value))
现在我们绘制这个:
ggplot(myresults_pct,
aes(x=manipulation, y=pct,fill=variable)) +
geom_col()+
scale_fill_grey()+
geom_text(aes(label = scales::percent(pct)),
position="stack",vjust=+2.1,col="firebrick",size=3)+
scale_y_continuous(label = scales::percent)
geom_text 中的重要参数是 position="stacked",并使用 vjust 来上下移动标签。(我提前为糟糕的文字颜色道歉..)。
推荐阅读
- seo - 确保文本在 webfont 加载期间保持可见 - TypeKit PageSpeed Insights
- javascript - 在 Node JS 中使用 multer 上传文件
- javascript - 从较大的选择中随机选择 2 张图像以叠加在一起?
- python - Django - 'ManyRelatedManager' 对象不可迭代
- c++ - C ++ Lambda谓词原因变量不能在没有指定捕获默认值的lambda中隐式捕获
- mysql - MySQL 嵌套 Select BETWEEN 多行
- python - Python中的聚类
- esp8266 - 在 ESP8266 上实现 CoAP 协议的 ESP-CoAP 库是否仍然有效?
- android - LineChart MarkerView 消失,当我在图表上拖动时,当我释放拖动时又出现
- javascript - Javascript中的重置按钮