Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: adding horizontal lines to ggplot2

I am using the ggplot2 library in R.

Suppose I have a graph that looks like this:

library(ggplot2)

ggplot(work) + geom_line(aes(x = var1, y = var2, group = 1)) +
               theme(axis.text.x = element_text(angle = 90)) +
               ggtitle("sample graph")

Is there a way to directly add a second line to this graph?

e.g.

ggplot(work) + geom_line(aes(x = var1, y = var2, group = 1)) +
               geom_line(aes(x = var1, y = mean(var2), group = 1)) +
               theme(axis.text.x = element_text(angle = 90)) +
               ggtitle("Sample graph")

Thanks

like image 656
stats_noob Avatar asked Jul 18 '26 19:07

stats_noob


1 Answers

Indeed it is possible:

library(ggplot2)
ggplot(mtcars, aes(x = mpg)) +
        geom_line(aes(y = hp), col = "red") +
        geom_line(aes(y = mean(hp)), col = "blue")

enter image description here

However, for specifically horizontal lines, I would use geom_hline intstead:

ggplot(mtcars, aes(x = mpg, y = hp)) +
        geom_line(col = "blue") +
        geom_hline(yintercept = mean(mtcars$hp), col = "red")

enter image description here

like image 130
bird Avatar answered Jul 21 '26 09:07

bird