R : add an average line to an existing plot

Flo picture Flo · Jul 21, 2016 · Viewed 35.2k times · Source

I have done an application RShiny with a plot using ggplot.

Now, I want to add an average line to the existing plot.

library(ggplot2)

A <- c(1:10)
B <- c(1,1,2,2,3,3,4,4,5,5)

donnees <- data.frame(A,B) 
datetime<-donnees[,2]
Indcatotvalue<-donnees[,1]
df<-donnees

mn<-tapply(donnees[,1],donnees[,2],mean)
moyenne <- data.frame(template=names(mn),mean=mn)

ggplot(data=df,
   aes_q(x=datetime,
         y=Indcatotvalue)) + geom_line() 

I have tried to add :

geom_line(aes(y = moyenne[,2], colour = "blue"))

or :

lines(moyenne[,1],moyenne[,2],col="blue")

but nothing happens :( I don't understand especially for the function "lines".

Thank you for your answer...

Answer

Simon picture Simon · Jul 21, 2016

When you say average line I'm assuming you want to plot a line that represents the average value of Y (Indcatotvalue). For that you want to use geom_hline() which plots horizontal lines on your graph:

ggplot(data=df,aes_q(x=datetime,y=Indcatotvalue)) +
  geom_line() +
  geom_hline(yintercept = mean(Indcatotvalue), color="blue")

Which, with the example numbers you gave, will give you a plot that looks like this:

plot with stepped with average line