7
votes

I am trying to draw a graph using ggplot, geom_poitrange. I have two groups, each one with two points and corresponding error values. the code I use is below:

    group<-c("A","A","B","B")
    val<-c(1.3,1.4, 1.2,1.5)
    SD<-c(0.3,0.8,0.6,0.5)
    RX<-c("X","Z","X","Z")

    a<-data.frame(group,val,SD,RX)
    ggplot(data=a)+
    geom_pointrange(aes(x=RX, y=val, ymin=(val-SD), ymax=(val + SD), 
    group=group, color=group, position_dodge(width=4)), size=1.5)

With this I obtain a nice graph, but the groups overlap. enter image description here

I wanted to offset them. I tried the following:

    geom_pointrange(aes(x=RX, y=val, ymin=(val-SD), ymax=(val + SD), 
    group=group, color=group, position_dodge(width=1)), size=1.5)

or

    geom_pointrange(aes(x=RX, y=val, ymin=(val-SD), ymax=(val + SD), 
    group=group, color=group, position="dodge"), size=1.5)

and variations of the above. Can anyone suggest what I am doing wrong? Thanks

1
(1) the position argument should not be inside aes, which is described in ?geom_pointrange and ?position_dodge; (2) your width is too large; (3) you don't need group because you already 'group' your data using color = group.Henrik
Thank you. It now works with the following line: 'ggplot(data=a)+ geom_pointrange(aes(x=RX, y=val, ymin=(val-SD), ymax=(val + SD), color=group), size=1.5, position = position_dodge(width=0.2))'Giuseppe Barbesino

1 Answers

7
votes

The OP provides two potential solutions. The first solution uses the position_dodge() function, which is close. The problem is it is in the wrong place in the argument list (not because width is too large).

Explicitly specify position = position_dodge(width = 1) after aes()

ggplot(data=a) +     
geom_pointrange(aes(x=RX, y=val, ymin=(val-SD), max=(val + SD), 
                                       group=group, color=group), 
position = position_dodge(width = 1), size=1.5)

Checking the API in help ?geom_pointrange(), you see that position comes after mapping, data and stat. The easiest thing to do here is be explicit as seen above. Otherwise you will get an error or warning like:

Warning: Ignoring unknown aesthetics 

or

Error: `data` must be a data frame, or other object coercible by `fortify()`, not an S3 object with class PositionDodge/Position/ggproto/gg

Why not position="dodge"?

If you try the second solution, you will get a warning telling you to try the first solution:

Warning message:
Width not defined. Set with `position_dodge(width = ?)` 

As far as I understand, dodging is written for bars and box plots and uses the width inherent to those objects. Lines don't have width so you need to explicitly specify how much dodging should happen.