Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
456 views
in Technique[技术] by (71.8m points)

r - Dodging points and error bars with ggplot

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...