3

I would like to make a red horizontal mean line in a line chart with ggplot2, but I don't know how to do that. It shouldn't represent the mean of the values of the column E.

I prove that but it didn't work:

ggplot(data = df3, aes(x = df3$timestamp, y = df3[,1], group = 1)) + 
  geom_line() + 
  ylab("values") + 
  xlab("time") + 
  geom_hline(yintercept=mean(df3[,1]))

The data frame is called df3, the x line time series is the column timestamp, the y line is the column metric E.

Here the data frame head:

           E               timestamp
11 -22.30933 2015-02-09 09:05:00.712
14 -22.17142 2015-02-09 09:06:00.703
17 -21.24673 2015-02-09 09:07:00.703
20 -21.58154 2015-02-09 09:08:00.702
23 -21.07082 2015-02-09 09:09:00.702
26 -22.49973 2015-02-09 09:10:00.702
zx8754
  • 52,746
  • 12
  • 114
  • 209
Michele Della Mea
  • 966
  • 2
  • 16
  • 35
  • 1
    If you have your data set to `df3`, you don't have to use `df3$` in front of the variable names inside the `aes`. So: `aes(x = timestamp, y = df3[,1], group = 1)` is just fine. – Jaap Jul 28 '15 at 07:45
  • 2
    reprocucible example would be nice. http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Henk Jul 28 '15 at 07:46
  • Why are you using `df3[,1]` twice? So once for the `geom_line()` and a second time for `geom_hline()`? It might be useful to see how `df3` looks like. – drmariod Jul 28 '15 at 07:49
  • 1
    Your code works fine, just need to add color in: `geom_hline(yintercept=mean(df3[,1]),col="red")` – zx8754 Jul 28 '15 at 08:08

1 Answers1

2

Broadly speaking you should be able to use the geom_line(stat = "hline", yintercept = "mean") as in the example below:

require(ggplot2)
ggplot(mtcars, aes(x = wt, y=mpg)) + 
  geom_point() +
  geom_line(stat = "hline", yintercept = "mean", colour = "red")

line

Konrad
  • 17,740
  • 16
  • 106
  • 167