我有这样一组数据;
Station;Species;
CamA;SpeciesA
CamA;SpeciesB
CamB;SpeciesA
等...
我想用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轴上显示摄影机,并填充物种?
谢谢!
答案 0 :(得分:1)
使用mtcars
作为示例数据集,获取百分比条形图的一种方法是将geom_bar
与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
与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")