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

Set breaks between values in continuous axis of ggplot

How can we set the breaks of continous axis every 2 numbers if we have a very big range of values in an axis and cannot set it manually?

p1 <- ggplot(mpg, aes(displ, hwy)) +
  geom_point()
p1 + scale_x_continuous(breaks = c(2, 4, 6))

>Solution :

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

From the ?scale_x_continuous help page, breaks can be (among other options)

A function that takes the limits as input and returns breaks as output

Here’s an anonymous function going from the (floored) min to the (ceilinged) max by 2:

ggplot(mpg, aes(displ, hwy)) +
  geom_point() + 
  scale_x_continuous(breaks = \(x) seq(floor(x[1]), ceiling(x[2]), by = 2))

Alternately you could still use seq for finer control, more customizable, less generalizable:

ggplot(mpg, aes(displ, hwy)) +
  geom_point() + 
  scale_x_continuous(breaks = seq(2, 6, by = 2))
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