Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Percentage in a original ggplot count barplot

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading