r - 如何在ggplot2中制作百分比条形图
问题描述
我有一组这样的数据;
Station;Species;
CamA;SpeciesA
CamA;SpeciesB
CamB;SpeciesA
ETC...
我想创建一个累积条形图,其中 x 轴上的相机站和添加的每个物种的百分比。我尝试了以下代码;
ggplot(data=data, aes(x=Station, y=Species, fill = Species))+ geom_col(position="stack") + theme(axis.text.x =element_text(angle=90)) + labs (x="Cameras", y= NULL, fill ="Species")
但显然我在 y 轴上没有百分比,只有物种名称 - 这最终是我编码的内容。
我怎么能有 y 轴上的百分比,x 轴上的相机和物种作为填充?
谢谢 !
解决方案
使用mtcars
示例数据集获取百分比条形图的一种方法是使用geom_bar
with position = "fill"
。
library(ggplot2)
library(dplyr)
mtcars2 <- mtcars
mtcars2$cyl = factor(mtcars2$cyl)
mtcars2$gear = factor(mtcars2$gear)
# Use geom_bar with position = "fill"
ggplot(data = mtcars2, aes(x = cyl, fill = gear)) +
geom_bar(position = "fill") +
scale_y_continuous(labels = scales::percent_format()) +
theme(axis.text.x = element_text(angle = 90)) +
labs(x = "Cameras", y = NULL, fill = "Species")
第二种方法是手动预先计算百分比并使用geom_col
with position="stack"
。
# Pre-compute pecentages
mtcars2_sum <- mtcars2 %>%
count(cyl, gear) %>%
group_by(cyl) %>%
mutate(pct = n / sum(n))
ggplot(data = mtcars2_sum, aes(x = cyl, y = pct, fill = gear)) +
geom_col(position = "stack") +
scale_y_continuous(labels = scales::percent_format()) +
theme(axis.text.x = element_text(angle = 90)) +
labs(x = "Cameras", y = NULL, fill = "Species")
推荐阅读
- arrays - 将 1x6 数组中的值填充到 _x6 数组中 Google 表格的 Google App 脚本
- python - 提出连续数学问题的程序
- sql - 将值检索到不同的列中
- reactjs - 更改设置文件后反应快速刷新不更新
- css - 转换框:内容框、边框框和笔划框“无效的属性值”Chrome 开发工具
- python - Python - 有没有办法绕过 python 的 http 中间人攻击保护?
- javascript - 使用formik时如何修复/清除react-select?
- scala - 向 Play 框架项目添加自定义项
- ruby-on-rails-5 - Sidekiq super_fetch - 获救的工作是如何执行的?
- excel - 将范围从一个工作表复制到另一个工作表不起作用