Reputation: 5897
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
Upvotes: 6
Views: 6376
Reputation: 3294
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")
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")
Upvotes: 13