0

I am trying to add a simple line to show the median and mean of my data in a ggplot2 bar chart.

Here is the code I have

library(ggplot2)
library(plyr)

data <- c(1,1,1,2,2,2,2,2,2,3,3,4,5)

count_data<- count(data)

mean <- mean(count_data)
med <- median(count_data)
ggplot(count_data) + 
  geom_bar(aes(x=x, y=freq), stat="identity", position="dodge") +
  geom_vline(aes(xintercept=mean)) + 
  #facet_wrap(~Year, nrow=1) + 
  theme_classic()

I do see my data alright, but the vline does not show up. Would you know what's wrong?

LBes
  • 3,366
  • 1
  • 32
  • 66

1 Answers1

2

I'm assuming you want the mean/median frequency, given you have created count_data. To do this I have explicitly called the freq variable when creating mean and med. The below therefore has both lines on the barplot.

If you actually want the mean/median of data, then it should just be mean(data), for example.

data <- c(1,1,1,2,2,2,2,2,2,3,3,4,5)

count_data<- plyr::count(data)

mean <- mean(count_data$freq)
med <- median(count_data$freq)
ggplot(count_data) + 
  geom_bar(aes(x=x, y=freq), stat="identity", position="dodge") +
  geom_vline(aes(xintercept = mean)) + 
  geom_vline(aes(xintercept = med)) +
  #facet_wrap(~Year, nrow=1) + 
  theme_classic()
Jaccar
  • 1,720
  • 17
  • 46
  • 1
    Great solution. You don't need to calculate the mean and median first, you can do this directly in the code to the same effect: *p + geom_vline(xintercept = mean(freq))* – glenn_in_boston Feb 03 '22 at 16:33