Convert abundance to percentage for geom_bar

Hello,
I would like to perform a geom_bar of the percentage of species per station.
However I only have abundance per station.
How can I go about getting the percentage that each species represents per station (percentage in relation to the total abundance per station and not in relation to the whole dataset)

In this example, station A1 has a total abundance of 8 and I would like to have a new percentage column where there will be for Atlanticus 0.25 [(2/8) * 100].

df <- tribble(
  ~zone, ~type, ~station, ~species, ~number,
  'A1', 'Adult', 1, 'Atlanticus', 2,
  'A1', 'Adult', 1, 'Olrikii', 1,
  'A1', 'Larvae', 2, 'Medius', 5,
  'A2', 'Larvae', 1, 'Glacialis', 7,
  'A2', 'Larvae', 2, 'Unidentified', 3, 
  'A2', 'Adult', 2, 'Glacialis', 2, 
  'A2', 'Larvae', 2, 'Medius', 4, 
  'A3', 'Zoo', 1, 'Capilatta', 17,
  'A3', 'Adult', 3, 'Olrikii', 1
)

The ideal would be to do this transformation directly by coding the ggplot but if you have to modify the dataset before it does not matter

Thanks very much

Here is one solution that does not change the original data but does the calculation before calling ggplot().

library(dplyr)
library(ggplot2)
df <- tribble(
  ~zone, ~type, ~station, ~species, ~number,
  'A1', 'Adult', 1, 'Atlanticus', 2,
  'A1', 'Adult', 1, 'Olrikii', 1,
  'A1', 'Larvae', 2, 'Medius', 5,
  'A2', 'Larvae', 1, 'Glacialis', 7,
  'A2', 'Larvae', 2, 'Unidentified', 3, 
  'A2', 'Adult', 2, 'Glacialis', 2, 
  'A2', 'Larvae', 2, 'Medius', 4, 
  'A3', 'Zoo', 1, 'Capilatta', 17,
  'A3', 'Adult', 3, 'Olrikii', 1
)

df %>% group_by(zone) %>% mutate(Percent = 100 * number/sum(number)) %>% 
  ggplot(aes(zone, y = Percent, fill = species)) + geom_col(position = "dodge")

Created on 2022-04-29 by the reprex package (v0.2.1)

Great thanks a lot it's exactly what I wanted !

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.