Search code examples
rggplot2bar-chartvline

Adding a line at the mean of the data, ggplot2


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?


Solution

  • 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()