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
position_dodge: Adjust position by dodging overlaps to the side.
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.
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).
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With