ggplot2:在离散轴上显示每第n个值 [英] ggplot2: display every nth value on discrete axis

查看:110
本文介绍了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))

这篇关于ggplot2:在离散轴上显示每第n个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆