Home > front end >  Set ggplot2 limits as relative ranges
Set ggplot2 limits as relative ranges

Time:01-14

I have 50 graphs to produce (plotting averages of lots of variables one by one) and was asked to normalize the scale range : i.e. the minimum and maximum value can vary but I want the difference between ymin and ymax to remain the same (say, 100)

here's an example :

#this works :

works<-mtcars%>%ggplot(aes(x=wt,y=mpg)) stat_summary(geom="line",size=2,col="blue",fun="mean") ylim(mean(mtcars$mpg)-50,mean(mtcars$mpg) 50) 

works
#this does not :
mtcars%>%ggplot(aes(x=wt,y=mpg)) stat_summary(geom="line",size=2,col="blue",fun="mean") ylim(mean(.data$y)-50,mean(.data$y) 50)

# neither does this

mtcars%>%ggplot(aes(x=wt,y=hp)) stat_summary(geom="line",size=2,col="blue",fun="mean") ylim(ymin,ymin 100)

I would like to avoid calling the variable directly as I have a lot of them but rather either a transformation of the y aesthethic or the keep the automatic ggplot scaling as "ymin" (ggplots calculates it somewhere for automatic cropping and a ggplot is a list so this element should be callable somehow) and call ymax relative to ymin or (even better but not sure it exists) specify automatic limits as a range (like "I want it centered - something" ) and keep "something" constant among all my graphs

do you have any idea ?

Have a nice day !

CodePudding user response:

You can do it by using the scale_y_continuous() function instead of ylim(). Its argument limits can accept a function changing existing, default limits. See the example below.

mtcars%>%
ggplot(aes(x=wt,y=mpg)) 
stat_summary(geom="line",size=2,col="blue",fun="mean") 
scale_y_continuous(limits = function(lim){c(lim[1]-50,lim[2] 50)})

CodePudding user response:

A tidy way to do this would be to define your own ggplot_add method:

add_range <- function(range) {
  structure(list(range = range), class = 'expander')
 }

ggplot_add.expander <- function(obj, p, name) {
  p   ylim(mean(sapply(ggplot_build(p)$data, function(x) mean(x$y)))   obj$range)
}

This then allows you to use whatever range above and below the mean of the data you like with an easy-to-use syntax:

mtcars %>%
  ggplot(aes(x = wt, y = mpg))   
  stat_summary(geom = "line", size = 2, col = "blue", fun = "mean")  
  add_range(c(-50, 50))

enter image description here

  • Related