首页 > 解决方案 > 如何在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 轴上的相机和物种作为填充?

谢谢 !

标签: rggplot2bar-chart

解决方案


使用mtcars示例数据集获取百分比条形图的一种方法是使用geom_barwith 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_colwith 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")


推荐阅读