How I can automate displaying only 1 in every n values on a discrete axis?
I can get every other value like this:
library(ggplot2)
my_breaks <- function(x, n = 2) {
return(x[c(TRUE, rep(FALSE, n - 1))])
}
ggplot(mpg, aes(x = class, y = cyl)) +
geom_point() +
scale_x_discrete(breaks = my_breaks)
But I don't think it's possible to specify the n
parameter to my_breaks
, is it?
Is this possible another way? I'm looking for a solution that works for both character and factor columns.
Not quite like that, but scale_x_discrete
can take a function as the breaks argument, so you we just need to adapt your code to make it a functional (a function that returns a function) and things will work:
every_nth = function(n) {
return(function(x) {x[c(TRUE, rep(FALSE, n - 1))]})
}
ggplot(mpg, aes(x = class, y = cyl)) +
geom_point() +
scale_x_discrete(breaks = every_nth(n = 3))
Since ggplot 3.3.0 it is also possible to solve the problem of dense labels on discrete axis by using scale_x_discrete(guide = guide_axis(n.dodge = 2))
, which gives (figure from documentation):
See the rewrite of axis code section of the release notes for more details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With