0

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

Lili
  • 547
  • 6
  • 19

2 Answers2

2

We could do it this way:

library(scales)
library(ggplot2)

ggplot(df, aes(factor(Depth), fill= Species)) + 
  geom_bar(position = "dodge", aes(y = (..count..)/sum(..count..))) + 
  scale_y_continuous(labels=percent)+
  scale_fill_grey() +
  theme_bw()

enter image description here

TarJae
  • 72,363
  • 6
  • 19
  • 66
2

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

Quinten
  • 35,235
  • 5
  • 20
  • 53
  • Is there any modification that could be done to represent only D monte without loosing the percentage? as in 0.5 would stil be around 60% represented DMonte? – Lili Nov 14 '22 at 18:59
  • Hi @Lili, You could add `filter(Species == 'DMonte')` after the `mutate`. Is that what you mean? – Quinten Nov 14 '22 at 19:06