Reputation: 8404
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))
Upvotes: 0
Views: 1873
Reputation: 145755
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
The scales
package offers breaks_width()
for exactly this purpose:
ggplot(mpg, aes(displ, hwy)) +
geom_point() +
scale_x_continuous(breaks = scales::breaks_width(2))
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))
Upvotes: 3