使用ggplot绘制误差线的问题

时间:2018-11-13 02:35:18

标签: r ggplot2 bar-chart

我试图将误差线绘制到我的柱状图中,但是它总是弹出错误 错误:In Ops.factor(val, stdev) : ‘-’ not meaningful for factors。如果我检查数据框的类,它们都是数字。代码:

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

1 个答案:

答案 0 :(得分:2)

问题在于您的数据是字符串。如下所示将其转换为数字。

y

enter image description here