Danny
Danny

Reputation: 488

Display every nth value on discrete axis

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.

Upvotes: 12

Views: 5790

Answers (2)

krassowski
krassowski

Reputation: 15409

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):

enter image description here

See the rewrite of axis code section of the release notes for more details.

Upvotes: 15

Gregor Thomas
Gregor Thomas

Reputation: 146020

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))

Upvotes: 32

Related Questions