Home > database >  Making a grouped bar chart in R
Making a grouped bar chart in R

Time:06-01

I am trying to produce a grouped bar chart in R and struggled to know how best to configure the data I have as there are a lot of variables.

This is the data set that I am using: This data is showing what number of individuals of each species (of each size group) contain the different types of material in their gut contents (empty, animal, plant, substrate)

This data is showing what number of individuals of each species (of each size group) contain the different types of material in their gut contents (empty, animal, plant, substrate)

I am trying to make something that looks like this. The two size classes at each site, and how many individuals were found to have empty guts, or various types of matter in their gut contents. The two size classes at each site, and how many individuals were found to have empty guts, or various types of matter in their gut contents.

Is it possible to make something like this in R? I hope I have made it clear enough for you to understand, if not, please let me know. Help would be greatly appreciated!

CodePudding user response:

Two steps:

  1. Change to long format (that's what ggplot expects)
  2. Use position = "dodge" to set your barplot as a grouped bar plot.
library(tidyr)
library(ggplot2)

df |>
  # Reshape data to long format
  pivot_longer(empty:substrate) |> 
  ggplot(aes(x = site, y = value, fill = name))  
  # Implement a grouped bar chart
  geom_bar(position = "dodge", stat = "identity")

Created on 2022-05-31 by the enter image description here

Data

df <- data.frame(site = c("1A", "1A", "1B", "1B", "2A", "2A", "2B", "2B"),
                 species = c("P", "P", "P", "P", "D", "D", "D", "D"),
                 empty = c(25,33,22,39,27,13,27,18),
                 animal = c(8,11,8,18,18,26,11,12),
                 plant = c(8,11,5,12,10,6,9,4),
                 substrate = c(4,4,1,2,5,1,6,1))
  • Related