Home > database >  Setting different coordinate limits (xlim or ylim) for different geoms
Setting different coordinate limits (xlim or ylim) for different geoms

Time:01-05

I am plotting multiple predictive values of my logistic regression given different values of my covariates. Essentially what I need to do is set a respective xlim() for each different geom plotted. Here is an example using 2 different geoms:

ggplot(mtcars,aes(x = mpg))  
  geom_point(aes(y = wt))  
  geom_smooth(aes(y = qsec))

Within this example, how could I restrict geom_point to only show specific values (say xlim(15,20)) while geom_smooth has a different (say xlim(25,30))? Can this be done?

CodePudding user response:

You can subset data using a function in place of a data.frame for the data parameter of a layer. This function will be provided the global data given as argument of ggplot, and the result will be used by the layer.

ggplot(mtcars,aes(x = mpg))  
  geom_point(
    aes(y = wt), 
    data = function(data) {
      data[data$mpg>=15 & data$mpg<=20,]
    }
  )  
  geom_smooth(aes(y = qsec))

CodePudding user response:

You could use ggplot_build to filter on both the geom layers their x values. So first filter for your first layer [[1]] and second layer [[2]] to show the respective ranges you want. Here is a reproducible example:

library(ggplot2)
p <- ggplot(mtcars,aes(x = mpg))  
  geom_point(aes(y = wt))  
  geom_smooth(aes(y = qsec))

q <- ggplot_build(p)

# first layer is geom point
q$data[[1]] <- q$data[[1]][q$data[[1]]$x >= 15 & q$data[[1]]$x <= 20, ]
# second layer is geom smooth
q$data[[2]] <- q$data[[2]][q$data[[2]]$x >= 25 & q$data[[2]]$x <= 30, ]

q <- ggplot_gtable(q)

plot(q)

Created on 2023-01-04 with reprex v2.0.2

  • Related