Skip to content

Instantly share code, notes, and snippets.

@lehostert
Last active March 23, 2021 04:23
Show Gist options
  • Save lehostert/1c820445371fd33fd47f9d4af82e8281 to your computer and use it in GitHub Desktop.
Save lehostert/1c820445371fd33fd47f9d4af82e8281 to your computer and use it in GitHub Desktop.
stacked bar plots

Stacked Bar Plot Example

Summary

This is an example of how to create a stacked bar plot with percent family from a fish data set. Using this example you will be able to take a full data set and compute the family proportions just before plotting without the need to save a new dataframe.

Dependencies

This is dependent on the dplyr and ggplot2 libraries.

Use

To run it either use the RStudio IDE to run it interactively or use Rscript at the command line.

Rscript.exe stacked_barplot_example.R

DFTBA

"Don't Forget To Be Awesome"

library(dplyr)
library(ggplot2)
## Example of a stacked bar plot with percentage calculated just prior to plotting.
fish <- read.table(text="site species count family
1 x 20 A
1 y 25 B
1 z 5 A
2 x 100 A
2 y 20 B
2 z 20 A
2 w 5 C
3 x 50 A
3 y 10 B", header=TRUE)
fish %>%
group_by(site, family) %>%
summarise(count = sum(count)) %>%
group_by(site) %>%
mutate(percent = 100*count/sum(count)) %>%
ggplot(aes(x = site, y = percent, fill = family, label = family)) +
geom_bar(stat = "identity")+
geom_text(size = 3, position = position_stack(vjust = 0.5))+
scale_fill_viridis_d(direction = -1)
ggsave("fish_stacked_barplot_by_family.png", width = 5, height = 5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment