1

I have a sample dataset here:

data = data.frame(Region = c(rep("Upper",50), rep("Lower", 50)),
                  Weight = c(rnorm(50, 2, 1), rnorm(50, 4, 1)))

I want to create a histogram in ggplot which the mean of each histogram overlaid with a red line.

ggplot(data=data, aes(x=Weight))+geom_histogram()+geom_vline(xintercept=mean(Weight), col="red")+facet_grid(Region~.)
Jade131621
  • 316
  • 1
  • 13

1 Answers1

3

Group your data by Region an calculate the mean for each respective Weight.

data <- data %>% group_by(Region) %>%  mutate(mean = mean(Weight))

ggplot(data, aes(x = Weight)) +
  geom_histogram() +
  facet_grid(Region~.) +
  geom_vline(aes(xintercept = mean, group = Region), colour = 'red')

enter image description here

Gnueghoidune
  • 1,237
  • 4
  • 13
  • I found this is useful! I have a follow up question, how to use geom_text() in this case to display the median value for each histogram. – monckeyyL Sep 28 '22 at 01:16