Reputation: 21
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)
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.
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!
Upvotes: 2
Views: 16994
Reputation: 41437
Maybe you want something like this:
library(tidyverse)
df %>%
pivot_longer(-(site:species)) %>%
ggplot(aes(x = name, y = value, fill = name)) +
geom_bar(stat = "identity") +
facet_wrap(~site) +
theme_bw() +
theme(legend.position = "bottom", legend.box = "horizontal", legend.title = element_blank())
Output:
For different colors you can use scale_fill_manual
like this:
library(tidyverse)
df %>%
pivot_longer(-(site:species)) %>%
ggplot(aes(x = name, y = value, fill = name)) +
geom_bar(stat = "identity") +
scale_fill_manual(values = c("Blue","Red", "Green", "Yellow")) +
facet_wrap(~site) +
theme_bw() +
theme(legend.position = "bottom", legend.box = "horizontal", legend.title = element_blank())
Output:
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))
Upvotes: 1
Reputation: 2462
Two steps:
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 reprex package (v2.0.1)
Upvotes: 2