Making a grouped barplot using ggplot

Hi everyone,

I'm fairly new to R and am really struggling to make a grouped barplot

This is the data I'm trying to use:
df_percentages<- data.frame(year= c(2014, 2015, 2016, 2017, 2018, 2019, 2020),
top_10 =c(53.3, 48.8,50.3,40.7,39.2,39.0,42.2),
less_equal_10 = c(5.0,6.0,5.2,5.0,5.2,7.2,5.5),
just_1= c(2.3,3.5,2.9,2.8,2.9,3.6,3.0))

I'm trying to make it something like this (made in excel for ease)

This is the code I'm using so far, and I'm not sure where I'm going wrong for something that is supposedly so easy...

ggplot(df_percentages, aes(fill=year)+
geom_bar(year= 'dodge', stat= 'identity')+
theme_minimal()+
labs(x= 'Year', y='Number of Recordings',
title= 'Observer Behaviour per year (% of total recordings') +
theme(plot.title = element_text(hjust = 0.5, size= 20, face= 'bold'))+
scale_fill_manual('Year', values= c('blue', 'red', 'yelow')))

Anyone know how to do this?
Thank you!
Jem

Hi @Jem_Powell

Here's how I would do it, by putting it into long-form at and using geom_col()

library(ggplot2)
library(dplyr)
library(tidyr)

df_percentages<- data.frame(year= c(2014, 2015, 2016, 2017, 2018, 2019, 2020),
top_10 =c(53.3, 48.8,50.3,40.7,39.2,39.0,42.2),
less_equal_10 = c(5.0,6.0,5.2,5.0,5.2,7.2,5.5),
just_1= c(2.3,3.5,2.9,2.8,2.9,3.6,3.0))

#make long format and order the category the way you want
df_perc_long <- df_percentages %>% 
pivot_longer(2:4, names_to = "category", values_to = "observations" ) %>% 
mutate(category = factor(category, levels = c('top_10', 'less_equal_10', 'just_1')))

df_perc_long %>% ggplot(aes(x=year, y=observations, fill = category))+
geom_col(position = "dodge" )+
theme_minimal()+
labs(x= 'Year', y='Number of Recordings',
title= 'Observer Behaviour per year (% of total recordings) ') +
theme(plot.title = element_text(hjust = 0.5, size= 20, face= 'bold'), 
legend.position = "bottom") +
scale_fill_manual('category', values= c('blue', 'red', 'yellow'))

Is this the result you are looking for? You can further tweak the appearance of the axis and labels.

JW

Great Thank you!

Jem

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.