ggplot2:在离散轴上显示每第n个值

问题描述:

我如何自动在离散轴上每n个值中仅显示1个?

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)

但是我认为不可能将n参数指定为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.

不太像,但是scale_x_discrete可以将函数用作breaks参数,因此您只需要调整代码以使其成为 functional (返回函数的函数),一切都会正常工作

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