将误差线添加到重叠的两个图上(ggplot2)

时间:2018-07-31 15:29:56

标签: r ggplot2

使用两个不同数据帧绘制的绘图出现问题。我需要绘制来自不同数据集的误差线图。

第一个数据帧:

dput(resudospobl)

structure(list(Poblacion = 
structure(c(1L, 1L, 2L, 2L), .Label = 
c("Carolina", 
"Lavalle"), class = "factor"), sexo = 
structure(c(1L, 2L, 1L, 
2L), .Label = c("hembra", "macho"), 
class = "factor"), N = c(960, 
960, 640, 640), IR = 
c(0.627976287904167, 
0.591445531573958, 
0.752046236173437, 0.748963332945312), 
sd = c(0.241332559805011, 
0.24103347180023, 0.194890181966294, 
0.20467196068143), se = 
c(0.00778897487518677, 
0.00777932185134039, 0.007703710857727, 
0.00809036961157182), 
ci = c(0.0152854016885121, 
0.0152664582011643, 0.0151276489859234, 
0.0158869243550959)), row.names = c(NA, 
-4L), class = "data.frame")

第二个数据帧:

dput(resudospobl2)

structure(list(Poblacion = 
structure(c(1L, 1L, 2L, 2L), .Label 
= c("Carolina", 
"Lavalle"), class = "factor"), Trat 
= structure(c(1L, 2L, 1L, 
2L), .Label = c("manzana", "uva"), 
class = "factor"), N = c(960, 
960, 640, 640), IR = 
c(0.658423422891667, 
0.560998396586458, 
0.758180928170312, 
0.742828640948437), sd = 
c(0.21174136546939, 
0.259656138696281, 
0.20285509360085, 
0.196492580813269), se = 
c(0.00683392318471805, 
0.00838036584092683, 
0.00801855163431666, 
0.00776705123368289
), ci = c(0.0134111693336726, 
0.0164459714183095, 
0.0157458965866789, 
0.0152520294295554)), row.names = 
c(NA, -4L), class = "data.frame")

其中se是标准错误。我的尝试是:

 ggplot()+
  #first layer
  geom_point(data=resudospobl, 
  aes(x=Poblacion, y=IR, colour=sexo) , 
  shape="square", size= 3)+
  #second layer
  geom_point(data=resudospobl2, 
  aes(x=Poblacion, y=IR, colour=Trat), 
  size=3)+
  #error bars
  geom_errorbar(data=resudospobl , aes( 
  ymin=IR-se, ymax=IR+se), size=0.3, 
  width=.1)+
  geom_errorbar(data=resudospobl2 , aes( 
  ymin=IR-se, ymax=IR+se), size=0.3, 
  width=.1)

结果是一条错误消息。以下是没有误差线的图,其中有两个按性别和治疗分组的人群:

theres two populations, grouped by sex and treatment

谢谢。

1 个答案:

答案 0 :(得分:1)

错误消息的关键部分是object 'x' not found

您没有在x中全局定义一个ggplot()变量。由于您也没有将参数传递给geom_errorbar(),因此ggplot无法绘制误差线,因为它不知道将其放置在x轴上的位置。

您的选择是将x放在每个错误栏图层中:

ggplot()+
     geom_point(data=resudospobl, 
                aes(x=Poblacion, y=IR, colour=sexo) , 
                shape="square", size= 3)+
     geom_point(data=resudospobl2, 
                aes(x=Poblacion, y=IR, colour=Trat), 
                size=3)+
     geom_errorbar(data=resudospobl , aes(x = Poblacion,
          ymin=IR-se, ymax=IR+se), size=0.3, 
          width=.1)+
     geom_errorbar(data=resudospobl2 , aes(x = Poblacion,
          ymin=IR-se, ymax=IR+se), size=0.3, 
          width=.1)

OR,因为您为两个数据集的所有图层使用相同的xyyminymax变量,所以可以在{{1 }},而不是在每个图层中单独

ggplot()