简体   繁体   中英

R : add an average line to an existing plot

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

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:

与平均线步进的情节

I have found the answer in this page :

groups.google.com/forum/#!topic/ggplot2/vd5n1jR9k40

The function stat_summary is perfect here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM