0

Been scouring the site (and others) for a solution to the problem pictured below. I can't get the error bars to move from their 'low' position, despite trying lots of different solutions to similar problems I have encountered here and elsewhere.

enter image description here

The problem occurs whether I produce one graph alone or the two and combine them with gridExtra.

Here is the code and a sample of each dataset included:

First dataset example:

Group      PSQI Time_Point
1 Control    2   Baseline
2 Control    2   Baseline
3 Control    2   Baseline
4 Control   13   Baseline
5 Control    1   Baseline
6 Control    7   Baseline

Second:

  Group    ESS Time_Point
1 Control   3   Baseline
2 Control   4   Baseline
3 Control   1   Baseline
4 Control   0   Baseline
5 Control   7   Baseline
6 Control  11   Baseline

Code:

library(gridExtra)
library(ggplot2)
library(grid)

p1 <- ggplot(PSQI_Graph,aes(fill=Group,y=PSQI,x=Time_Point)) +
    geom_bar(position="dodge",stat="identity", width = 0.50) +
    stat_summary(fun.data = mean_cl_normal, geom = "errorbar", position = 
position_dodge(.5), width = .25)+
    guides(fill = F)+
    scale_y_continuous(name = "Mean PSQI Score", limits=c(0,25))+
    xlab("Time Point") +
    guides(fill = guide_legend(keywidth = 1.5, keyheight = 1))+
    theme_bw()

Would really like to get this data out, so would appreciate any suggestions.

2
  • Welcome to SO. Please edit your question and provide a reproducible example that showcases your problem and that is ready to copy-paste-run in a new R session. Commented Jun 9, 2017 at 12:28
  • If you calculate mean for both levels in each facet, you'll notice that the center of the error bars is right where mean is. Commented Jun 9, 2017 at 12:57

1 Answer 1

2

It would be better to use geom_errorbar. First, you'll have to make a new data.frame with one line per bar, including the standard error (I added an "After" timepoint to show how this looks):

    Group PSQI Time_Point StdErr
1 Control 4.50   Baseline   1.91
2 Control 7.17      After   0.79

Then, this ggplot call will work:

ggplot(psqi, aes(fill=Group, y=PSQI, x=Time_Point, ymin=PSQI-StdErr, ymax=PSQI+StdErr)) + #the ymin and ymax parameters here tell it where to put the top and bottom error bars
    geom_bar(stat="identity") +
    geom_errorbar() #you can change the width and thickness of the bars

Yielding this image:

Sign up to request clarification or add additional context in comments.

1 Comment

Worked perfectly! Legend!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.