Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

ggplot2

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.

like image 431
MikeTP Avatar asked May 11 '12 21:05

MikeTP


2 Answers

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

enter image description here

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

enter image description here

like image 190
Brian Diggs Avatar answered Oct 20 '22 01:10

Brian Diggs


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

enter image description here

like image 43
Sandy Muspratt Avatar answered Oct 19 '22 23:10

Sandy Muspratt