ggplot 2 facet_grid"free_y"但强制Y轴舍入到最接近的整数

Mik*_*eTP 18 r ggplot2

使用时:

facet_grid(SomeGroup ~, scales="free_y") 
Run Code Online (Sandbox Code Playgroud)

是否可以指定虽然您希望标尺"自由",但您希望它们四舍五入到最接近的整数?

任何援助都将受到极大的赞赏.

Bri*_*ggs 31

鉴于breaks在scale中可以采用一个函数,我想你可以将基本的破解算法包装在一个不允许非整数的函数中.

从一个例子开始:

ggplot(mtcars, aes(wt, mpg)) + 
geom_point() + 
facet_grid(am+cyl~., scales="free_y")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

看看如何scales::pretty_breaks放在一起,创建一个包装它的函数,只允许整数突破:

library("scales")
integer_breaks <- function(n = 5, ...) {
  breaker <- pretty_breaks(n, ...)
  function(x) {
     breaks <- breaker(x)
     breaks[breaks == floor(breaks)]
  }
}
Run Code Online (Sandbox Code Playgroud)

现在使用返回的breaks函数作为比例中的函数

ggplot(mtcars, aes(wt, mpg)) + 
geom_point() + 
facet_grid(am+cyl~., scales="free_y") +
scale_y_continuous(breaks = integer_breaks())
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


San*_*att 7

我可能会在这里遗漏一些东西,但我会做这样的事情.

library(ggplot2)
ggplot(mtcars, aes(wt, mpg)) + 
   geom_point() + 
   facet_grid(am+cyl~., scales="free_y", space = "free_y") +
   scale_y_continuous(breaks = seq(0, 40, 2), expand = c(0, 1))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述