Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2: display every nth value on discrete axis

Tags:

r

ggplot2

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.

like image 394
Danny Avatar asked Oct 21 '18 21:10

Danny


2 Answers

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))
like image 128
Gregor Thomas Avatar answered Sep 22 '22 00:09

Gregor Thomas


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.

like image 38
krassowski Avatar answered Sep 22 '22 00:09

krassowski