7

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

3
  • 5
    It would be easier to help if you create a small reproducible example along with expected output. Read about how to give a reproducible example. Commented May 13, 2021 at 5:11
  • 1
    A few typos in your code : forgotten ) - it seems to work with edits above. As suggested by @Ronak Shah, please supply MRE if it still doesn't work as you'd like Commented May 13, 2021 at 5:39
  • geom_hline(yintercept = mean(var2))? Commented May 13, 2021 at 5:51

1 Answer 1

14

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.