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

前端 未结 4 909
隐瞒了意图╮
隐瞒了意图╮ 2020-11-30 12:10

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

4条回答
  •  孤城傲影
    2020-11-30 12:56

    The first change I reformatted the code according to the advanced R style guide.

    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
    

    Now when we look at the data we see that day is a factor and everything else is the same.

    str(my_data)
    

    To remove blank space from the plot I converted the day column to factors. CHECK that the levels are in the proper order before proceeding.

    my_data$day <- as.factor(my_data$day) 
    levels(my_data$day)
    

    The next change I made was defining y in your aes arguments. As I'm sure you are aware, this lets ggplot know where to look for y values. Then I changed the position argument to "dodge" and added the stat="identity" argument. The "identity" argument tells ggplot to plot y at x. geom_errorbar inherits the dodge position from geom_bar so you can leave it unspecified, but geom_point does not so you must specify that value. The default dodge is position_dodge(.9).

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

提交回复
热议问题