0

I was trying to plot error bars to my bar plot, but it always pops the error error: In Ops.factor(val, stdev) : ‘-’ not meaningful for factors. If I check the class of my data frame they are all numeric. Code:

library(ggplot2)
library(scales)
dataset <- c("gg1", "gg2","gg3")
group <- c("A 1", "A 1", "A 1", "Y 2", "Y 2", "Y 2", "P 3", "P 3", "P 3")
val <- c("5", "4", "3", "2", "4", "5", "2", "8", "6")
stdev <- c("0.5", "0.1", "0.5","0.07","0.2", "0.5","0.2","0.4", "0.8")
dat_frame <- data.frame(dataset, group, val, stdev)  
dat_frame  

p8 = ggplot(dat_frame, 
            aes(fill=dataset, y=val, x=group, ymin=val-stdev, ymax=val+stdev)) + 
     geom_bar(position="dodge", stat="identity") + 
     scale_fill_manual(values=c('gg1'='red', 'gg2'='green', 'gg3'='grey'))

p9 = p8 + coord_cartesian(ylim=c(0,7))
p9 + geom_errorbar(width=.08, position=position_dodge(0.5))

barplot

3
  • Your code has the standard deviation and the values as characters. Convert them to numeric Commented Nov 13, 2018 at 2:42
  • Questions about code are off topic here. You have a reproducible example (thanks!), so this will be on topic on Stack Overflow. I will migrate it there. Commented Nov 13, 2018 at 2:45
  • I assume this is just example data. Otherwise as @Marius says below, you would just create numeric vectors. Commented Nov 13, 2018 at 3:31

1 Answer 1

3

The problem is that your data is a string. Convert it to numeric as shown below.

library(tidyverse)
library(scales) 
dataset <- c("gg1", "gg2","gg3") 
group <- c("A 1", "A 1", "A 1", "Y 2", "Y 2", "Y 2", "P 3", "P 3", "P 3") 
val <- c("5", "4", "3", "2", "4", "5", "2", "8", "6") %>% as.numeric
stdev <- c("0.5", "0.1", "0.5","0.07","0.2", "0.5","0.2","0.4", "0.8") %>% as.numeric
dat_frame <- data.frame(dataset, group, val, stdev) %>% as.tibble()


p8 = ggplot(dat_frame, aes(fill=dataset, y=val, x=group, ymin = val-stdev, ymax = val+stdev))+
  geom_bar(position="dodge", stat="identity", width = 1)+
  scale_fill_manual(values=c('gg1' = 'red','gg2' = 'green','gg3'='grey'))

p8+geom_errorbar(width = .08, position = position_dodge(1))

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

Or just create the vectors as numeric in the first place by not wrapping the values in quotes: c(0.5, 0.1, 0.5, 0.07, 0.2, 0.5, 0.2, 0.4, 0.8)
Yes, don't be like me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.