Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"))
  
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading