Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dodging points and error bars with ggplot

Tags:

r

ggplot2

Consider this data (note that foo is actually a factor.):

foo bar outcome ci
1   a   0.683333333 0.247447165
2   b   0.941666667 0.180356565
3   c   0.783333333 0.335337789
1   d   0.866666667 0.204453706
2   e   0.45    0.303059647
3   f   0.325   0.340780173

I want to plot multiple bars per foo value, with their outcome and error bars with CI. Here's what I do:

ggplot(ex, aes(foo, outcome, label = bar)) + 
  geom_point(position = position_dodge(.1)) + 
  geom_errorbar(aes(ymin = outcome - ci, ymax = outcome + ci), position = position_dodge(.1)) + 
  geom_text(hjust = 2)

I get:

But I wanted it to dodge the error bars and points so I can see the overlap. Using position_jitter did that, but it was totally random (or "clunky") — I don't want that.

How can I offset the individual observations?

Or is this a bug with ggplot? The example here also shows this error.

like image 806
slhck Avatar asked Sep 11 '14 13:09

slhck


1 Answers

One possibility is to group by 'bar'. Note that I also dodge the geom_text.

dodge <- position_dodge(.1)

ggplot(data = df, aes(x = foo, y = outcome, group = bar, label = bar)) + 
  geom_point(position = dodge) + 
  geom_errorbar(aes(ymin = outcome - ci, ymax = outcome + ci), position = dodge) + 
  geom_text(hjust = 2, position = dodge)

enter image description here

like image 181
Henrik Avatar answered Oct 15 '22 06:10

Henrik