Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add an average line to an existing plot

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".

like image 554
Flo Avatar asked Jul 21 '16 10:07

Flo


Video Answer


2 Answers

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

like image 135
Simon Avatar answered Oct 05 '22 23:10

Simon


The function stat_summary is perfect here.

I have found the answer in this page groups.google from Brian Diggs:

p + stat_summary(aes(group=bucket), fun.y=mean, geom="line", colour="green")

You need to set the group to the faceting variable explicitly since otherwise it will be type and bucket (which looks like type since type is nested in bucket).

like image 28
Flo Avatar answered Oct 06 '22 00:10

Flo