Eléonore Zittoun
Eléonore Zittoun

Reputation: 11

How to make a barplot of percentages in ggplot2

I have a set of data as such;

Station;Species;

CamA;SpeciesA

CamA;SpeciesB

CamB;SpeciesA

etc...

I would like to create a cumulative barplot with the cameras station in x axis and the percentage of each species added. I have tried the following code;

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

And end up with the following graph; enter image description here

But clearly I don't have a percentage on the y axis, just the species name - which is in the end what I have coded for..

How could I have the percentages on the y axis, the cameras on the x axis and the species as a fill?

Thanks !

Upvotes: 0

Views: 130

Answers (1)

stefan
stefan

Reputation: 124148

Using mtcars as example dataset one approach to get a barplot of percentages is to use 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")

A second approach would be to manually pre-compute the percentages and make use of 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")

Upvotes: 1

Related Questions