Connect mean points of error bars

前端 未结 3 1860
萌比男神i
萌比男神i 2021-01-15 19:08

In ggplot2 I\'m attempting a simple thing that I just can\'t get for some reason. I have adjusted means and SE in a data frame and want to plot the means, error bars and th

3条回答
  •  佛祖请我去吃肉
    2021-01-15 20:08

    If you remove the grouping by group within the ggplot call and set x = as.numeric(group ) within the call to geom_line, the it works.

    Also, you don't need to re-reference data1 within geom_line

    ggplot(data1, aes(x=group, y=estimate)) + 
      geom_errorbar(aes(ymin=estimate-SE, ymax=estimate+SE), 
      colour="black", width=.1, position=pd) +
      geom_line( aes(x=as.numeric(group), y=estimate)) + 
      geom_point(position=pd, size=4)
    

    enter image description here

    If you group by group, then you only have one value for geom_line to create a line from, hence the error message. The same error occurs if ggplot is considering the x or y mapping variables as a factor - this is because if you code a variable as a factor R (and ggplot) will consider them independent groups, and not connect the points - this is sensible default behaiviour.

    EDIT - with alphabetic factor labels

    This will work with alphabetic factor labels due to the way factors are coded internally by R (ie as.numeric(factor) returns numbers not the factor labels)

    ie.e

    Changing group to a, b, c

    levels(data1[['group']]) <- letters[1:3] 
    ggplot(data1, aes(x=group, y=estimate)) + 
      geom_errorbar(aes(ymin=estimate-SE, ymax=estimate+SE), 
      colour="black", width=.1, position=pd) +
      geom_line( aes(x=as.numeric(group), y=estimate)) + 
      geom_point(position=pd, size=4)
    

    enter image description here

提交回复
热议问题