jester_in_yellow
jester_in_yellow

Reputation: 29

R - two factor ggplot2 bargraph

I have a dataframe (df) with two factors:

f1,f2,value,    
A, 1, .5,
A, 1, .7,
A, 2, .2,
A, 2, .4,
B, 1, .3,
B, 1, .5,
B, 2, .1,
B, 2, .3,

I'd like to represent this data where 'f1' is on the x-axis and the data is broken up by 'f2' with 2 bars representing the means of the 'value' and sd error bars by factor 'f2.'

I.e. 'A' has two separate columns (.6 & .3) and 'B'; likewise (.4 & .2) with associative error bars.

I can always reshape the data to try to make this work, but I was wondering if there is a simpler way of going about this. I've seen some similar things in other threads but nothing that works just quite right.

Thanks so much for all your help!

Upvotes: 0

Views: 45

Answers (1)

Ben
Ben

Reputation: 30474

library(tidyverse)
library(ggplot2)

df %>%
  group_by(f1, f2) %>%
  summarise(mean = mean(value),
            SD = sd(value),
            n = n(),
            SE = SD/sqrt(n)) %>%
  ggplot(aes(x = f1, y = mean, group = f2, fill = f2)) +
    geom_bar(stat = "identity", position = "dodge", width = .5) +
    geom_errorbar(aes(ymax = mean + SE, ymin = mean - SE), position = position_dodge(.5), width = .2)

Plot

plot based on summarised data

Upvotes: 1

Related Questions