Skip to content

Instantly share code, notes, and snippets.

@matthewfeickert
Forked from lehostert/README.md
Last active March 23, 2021 04:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthewfeickert/065d69795915a8e3e3d8aa7172338b18 to your computer and use it in GitHub Desktop.
Save matthewfeickert/065d69795915a8e3e3d8aa7172338b18 to your computer and use it in GitHub Desktop.
stacked bar plots

Stacked Bar Plot Example

Binder

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"

install.packages("dplyr")
install.packages("ggplot2")
r-2021-03-01
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