Jackson Walker
Jackson Walker

Reputation: 157

How do I add separate errorbars in ggplot to each item on the X axis?

I have this graph:

Male and Female Heights

Which shows male and female heights along with the confidence interval of 95% for the mean. There's an issue tho, I can't seem to show one confidence interval for Males and one for Females. Both of the errorbars appear on both labels in the x axis. Would you be able to help me adjust me code to show the female CI (in blue) on the Female range, and the male CI (in red) for the Male range?

Here's my plot code:

gSE <- ggplot(data = sample.Height, aes(x=sample, y=heightIn)) +
  geom_point() + 
  geom_errorbar(aes(ymin=heightFemale.sampleMean-0.7970899, ymax=heightFemale.sampleMean+0.7970899), colour="blue", width=.1) +
  geom_errorbar(aes(ymin=heightMale.sampleMean-1.0322975, ymax=heightMale.sampleMean+1.0322975), colour="red", width=.1) +
  labs(title = "Male and Female Heights", x = "Gender", y = "Heights in Inches") +
  theme_light()
gSE

Thank you,

Upvotes: 1

Views: 296

Answers (1)

Ben
Ben

Reputation: 30474

Would first make a simple table of your mean and SE to use with geom_errorbar. Then you only need to have geom_errorbar included once in your ggplot.

Here's an example with made up data:

library(tidyverse)

sample.Stats <- sample.Height %>%
  group_by(sample) %>%
  summarise_all(funs(mean, se = sd(.)/sqrt(n())))

gSE <- ggplot() +
  geom_point(data = sample.Height, aes(x=sample, y=heightIn)) + 
  geom_errorbar(data=sample.Stats, aes(x=sample, ymin=mean-se, ymax=mean+se, color=sample), width=.1) +
  labs(title = "Male and Female Heights", x = "Gender", y = "Heights in Inches") +
  theme_light()

gSE

Plot

plot with error bars

Data

sample.Height <- data.frame(
  sample = c("Female", "Female", "Female", "Male", "Male", "Male"),
  heightIn = c(61, 60, 59, 66, 72, 70)
)

Upvotes: 1

Related Questions