Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using position_dodge with geom_pointrange

Tags:

r

ggplot2

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

like image 297
Giuseppe Barbesino Avatar asked May 13 '17 18:05

Giuseppe Barbesino


People also ask

What does Position_dodge do in R?

position_dodge: Adjust position by dodging overlaps to the side.

What does Dodge do in Ggplot?

Dodging preserves the vertical position of an geom while adjusting the horizontal position. position_dodge() requires the grouping variable to be be specified in the global or geom_* layer.


1 Answers

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.

like image 198
Ari Anisfeld Avatar answered Sep 24 '22 15:09

Ari Anisfeld