如何在ggplot2中制作百分比条形图

时间:2020-08-09 07:46:07

标签: r ggplot2 bar-chart

我有这样一组数据;

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")

最后得到下图; enter image description here

但是很明显,我在y轴上没有百分比,只是种类名称-最终是我编写的代码。

如何在y轴上显示百分比,在x轴上显示摄影机,并填充物种?

谢谢!

1 个答案:

答案 0 :(得分:1)

使用mtcars作为示例数据集,获取百分比条形图的一种方法是将geom_barposition = "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_colposition="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")

相关问题