Grouped Barplot of Summarized Means with Ggplot2

55 views Asked by At

I feel like I'm missing something very basic but any advice is appreciated.

I have a large dataset with 19 variables, both categorical and numerical. I want to produce a plot with three of the variables (since they share a unit) averaged and arranged by factor. Fake sample data:

Sex    Low Freq      High Freq      Bandwidth
M       3000         4011           1011
M       3000         3600           600 
M       2790         4237           1447
F       2700         3300           500
F       2900         4517           617
F       2813         3857           1044

I have tried:

ggplot(TripleSongAverages, aes(x=factor(Sex), y='Low Freq', 'High Freq', 'Bandwidth')) + stat_summary(fun.y="mean", geom="bar") 

But that only produces a plot with the first variable.

1

There are 1 answers

3
Duck On

I would suggest using a tidyverse approach reshaping the data and computing mean values. Here the code:

library(tidyverse)
#Data
df <- structure(list(Sex = c("M", "M", "M", "F", "F", "F"), Low.Freq = c(3000, 
3000, 2790, 2700, 2900, 2813), High.Freq = c(4011, 3600, 4237, 
3300, 4517, 3857), Bandwidth = c(1011, 600, 1447, 500, 617, 1044
)), class = "data.frame", row.names = c(NA, -6L))

Code:

#Reshape data and plot
df %>% pivot_longer(cols = -Sex) %>%
  group_by(Sex,name) %>%
  summarise(Mean=mean(value,na.rm=T)) %>%
  #Plot
  ggplot(aes(x=factor(Sex), y=Mean,fill=name)) +
  geom_bar(stat='identity',position = position_dodge(0.9)) 

Output:

enter image description here