简体   繁体   中英

ggplot 2 facet_grid “free_y” but forcing Y axis to be rounded to nearest whole number

When using:

facet_grid(SomeGroup ~, scales="free_y") 

Is it possible to specify that although you want the scales to be "free" you want them to be in rounded to the nearest whole numbers?

Any assistance woudl be greatly appreciated.

Given that breaks in scales can take a function, I would imagine that you could wrap the basic breaking algorithm in a function that doesn't allow non-integers.

Start with an example:

ggplot(mtcars, aes(wt, mpg)) + 
geom_point() + 
facet_grid(am+cyl~., scales="free_y")

在此输入图像描述

Looking at how scales::pretty_breaks is put together, make a function that wraps it and only allows integer breaks through:

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

Now use the function this returns as the breaks function in the scale

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

在此输入图像描述

I might be missing something here, but I would do something like this.

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

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM