I have this code:
tbl <- with(mydata, table(Species, Depth))
library(ggplot2)
ggplot(as.data.frame(tbl), aes(factor(Depth), Freq, fill = Species)) +
geom_col(position = 'dodge')
and this dataframe
Site Depth Substrate PoePres HaliPres Species
1 2 0.5 Sand 0 1 DMonte
2 2 0.5 Sand 0 1 DMonte
3 2 0.5 Sand 0 1 DMonte
4 2 0.5 Sand 0 1 DMonte
5 2 0.5 Sand 0 1 DMonte
6 2 0.5 Sand 0 1 DSandi
7 2 0.5 Sand 0 1 DSandi
8 2 0.5 Sand 0 1 DSandi
9 7 0.6 Sand 0 1 DMonte
10 7 0.6 Sand 0 1 DMonte
11 7 0.6 Sand 0 1 DMonte
That I took from this other question: Bar plot for count data by group in R
I would like to know how I could plot percentage per group (‘Depth’ in this case) rather than counts.
Thanks
>Solution :
Another option by first calculate the percentage value per group_by and use percent from scales to create percentage axis like this:
library(ggplot2)
library(dplyr)
library(scales)
mydata %>%
count(Species, Depth) %>%
group_by(Depth) %>%
mutate(pct = n / sum(n)) %>%
ggplot(aes(x = factor(Depth), y = pct, fill=factor(Species))) +
geom_col(position="dodge") +
scale_y_continuous(labels = percent) +
labs(x = 'Depth', fill = 'Species')

Created on 2022-11-14 with reprex v2.0.2