How to manually add a tick mark in ggplot2?

I am quite new to the ggplot2 world in R, so I am trying to get familiar with the technicalities of plotting with ggplot2. In particular, I have a problem, which can be replicated by the following MWE:

ggplot(data.frame(x = c(1:10), y = c(1:10)), aes(x = c(1:10), y = c(1:10))) +
  geom_line() +
  geom_hline(aes(yintercept = 6), lty = 2)

This generates a simple graph of a diagonal line with a horizontal dashed line that cuts the y-axis at 6.

I would like to know whether there is a way to add a tick mark of 6 on the y-axis? In other words, say I simply showed this plot to a person without the code. I want the person to know that the horizontal dashed line cuts the y-axis at 6, which is not easily seen since 6 is not labelled currently.

Any intuitive suggestions will be greatly appreciated 🙂

>Solution :

You can use scale_y_continuous and give it all the points where you’d want a tick in the breaks argument.

library(ggplot2)
ggplot(data.frame(x = c(1:10), y = c(1:10)), aes(x = x, y = y)) +
  geom_line() +
  geom_hline(aes(yintercept = 6), lty = 2) + 
  scale_y_continuous(breaks = c(2, 4, 6, 8, 10))

in this specific example there is lots of "empty space" and you might consider adding the number within the plot using geom_text or geom_label if you think that is, what people should take away from your plot:

library(ggplot2)
ggplot(data.frame(x = c(1:10), y = c(1:10)), aes(x = x, y = y)) +
  geom_line() +
  geom_hline(aes(yintercept = 6), lty = 2) + 
  #scale_y_continuous(breaks = c(2, 4, 6, 8, 10)) +
  geom_label(aes(x=2, y=6, label = "line at y = 6.0"))
  

Leave a Reply