Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

r - How to make dodge in geom_bar agree with dodge in geom_errorbar, geom_point

I have a dataset where measurements are made for different groups at different days.

I want to have side by side bars representing the measurements at the different days for the different groups with the groups of bars spaced according to day of measurement with errorbars overlaid to them.

I'm having trouble with making the dodging in geom_bar agree with the dodge on geom_errorbar.

Here is a simple piece of code:

days          = data.frame(day=c(0,1,8,15));
groups        = data.frame(group=c("A","B","C","D", "E"), means=seq(0,1,length=5));


my_data       = merge(days, groups);


my_data$mid   = exp(my_data$means+rnorm(nrow(my_data), sd=0.25));
my_data$sigma = 0.1;


png(file="bar_and_errors_example.png", height=900, width=1200);
plot(ggplot(my_data, aes(x=day, weight=mid, ymin=mid-sigma, ymax=mid+sigma, fill=group)) +
     geom_bar      (position=position_dodge(width=0.5))                                   +
     geom_errorbar (position=position_dodge(width=0.5), colour="black")                   +
     geom_point    (position=position_dodge(width=0.5), aes(y=mid, colour=group)));
dev.off();

In the plot, the errorsegments appears with a fixed offset from its bar (sorry, no plots allowed for newbies even if ggplot2 is the subject).

When binwidth is adjusted in geom_bar, the offset is not fixed and changes from day to day.

Notice, that geom_errorbar and geom_point dodge in tandem. How do I get geom_bar to agree with the other two?

Any help appreciated.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The alignment problems are due, in part, to your bars not representing the data you intend. The following lines up correctly:

ggplot(my_data, aes(x=day, weight=mid, ymin=mid-sigma, ymax=mid+sigma, fill=group)) +
     geom_bar      (position=position_dodge(), aes(y=mid), stat="identity") +
     geom_errorbar (position=position_dodge(width=0.9), colour="black") +
     geom_point    (position=position_dodge(width=0.9), aes(y=mid, colour=group))

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...