neuroandstats
neuroandstats

Reputation: 124

Need to make a bar plot with two columns of data from a data.frame

I am trying to make a bar graph of two columns from a data.frame side by side of each other. I have tried:

barplot(data.frame$data1, data.frame$data2, data=data.frame)

here is data:   
   Neutral Emotional
1   0.790   1.6400
2   0.051   0.0880
3   0.891   2.7200
4   0.430   1.1800
5   -0.009  -0.6000

but it makes a ton of bars instead of just two. I am trying to have two bars, one with neutral one with emotional and error bars representing SEM.

Upvotes: 0

Views: 63

Answers (2)

akrun
akrun

Reputation: 886948

An option would be to gather into 'long' format and then use geom_bar from ggplot2

library(tidyverse)
library(ggplot2)
gather(df1) %>% 
    ggplot(., aes(x = key, y = value)) +
        geom_bar(stat = 'identity')

If we also need an error bar, then

gather(df1) %>% 
     ggplot(., aes(x = key, y = value)) +
         stat_summary(fun.y = mean, geom = "bar") + 
         stat_summary(fun.data = mean_se, geom = "errorbar")

enter image description here

data

df1 <- structure(list(Neutral = c(0.79, 0.051, 0.891, 0.43), Emotional = c(1.64, 
0.088, 2.72, 1.18)), class = "data.frame", row.names = c("1", 
"2", "3", "4"))

Upvotes: 1

neilfws
neilfws

Reputation: 33772

Ways to achieve this result are discussed in this guide. Note that they recommend ggplot2 over barplot.

To get the chart with error bars for standard error of the mean:

library(tidyverse)

data.frame %>% 
  gather(Var, Val) %>% 
  group_by(Var) %>% 
  summarise(Mean = mean(Val), 
            SD = sd(Val), 
            SE = SD/sqrt(n())) %>% 
  ggplot(aes(Var, Mean)) + 
  geom_col() + 
  geom_errorbar(aes(ymin = Mean - SE, 
                    ymax = Mean + SE),
                width = 0.5)

Result:

enter image description here

However: note that so-called "dynamite plots" are not well-regarded by data visualisation experts. For small numbers of samples, it is better to show the range using geom_boxplot or geom_jitter.

Boxplot:

data.frame %>% 
  gather(Var, Val) %>% 
  ggplot(aes(Var, Val)) + 
  geom_boxplot()

enter image description here

Jitter with mean:

data.frame %>% 
  gather(Var, Val) %>% 
  ggplot(aes(Var, Val)) + 
  geom_jitter(width = 0.2) + 
  stat_summary(geom = "crossbar", 
               fun.y = mean, 
               fun.ymax = mean, 
               fun.ymin = mean, 
               color = "red", 
               width = 0.4)

enter image description here

Upvotes: 1

Related Questions