Search code examples
rggplot2ggforce

Defining y limits on a x-zoom graph with facet_zoom


I am trying to make a zoomed graph, on a x-axis of a geom_point() + geom_smooth() graph. I am able to obtain quite easily a graph I am looking for, just typing:

facet_zoom(xlim = c(0.05, 0.2))

But I would like to have the possibility to define also the ylim of the zoomed graph, mantaining the same configuration. The problem is that if I add also ylim() I get the zoomed graph on the y axis and not longer on the x one. I read some tutorial and guides online but I was not able to obtain a simple ylim definition on the y-axis graph.

Is there any options allwing to to that? I report you the code and the graph I got with the one I would like to obtain + two unsuccessfull trials I made.

Below, the running code:

#DATASET CREATION AND NAMES ASSIGNATION
Dati <- data.frame(V1 = c(0.2, 0.3, 0.4, 0.5, 0.1, 0.05, 0.1, 0),
                   V2 = c(11.25, 7.15, 5.5, 2.5, 30.75, 55.5, 34.5, 97))
colnames(Dati) <- c("cat", "vix")


#PACKAGES LOADING
library(ggplot2)
attach(Dati)

library(ggforce)
library(tidyverse)


#GRAPH CREATION
Graph1 <- ggplot(data=Dati, aes(x=`cat`, y=`vix`)) + geom_point(aes(color = "red"), shape = 1, size = 3.0, stroke = 1.5) + 
scale_color_manual(values=c('#f92410', '#644196')) + geom_smooth(aes(level=0.95, span = 0.8))  + 
theme(legend.position = "null") + 
geom_vline(xintercept = 0.2,  linetype="dashed", color = "red") +
facet_zoom(xlim = c(0.05, 0.2))

#facet_zoom(ylim = c(0, 80), xlim = c(0.05, 0.2), split = TRUE) #it creates a split with 4 graphs
#facet_zoom(ylim = c(0, 80), xlim = c(0.05, 0.2)) #it transfers on the y-axis the zoom

Graph1

Output graph:

enter image description here

Graph I would like to get, by defining the y-limits:

enter image description here


Solution

  • You could achieve your desires result by setting the ylim but also horizontal = FALSE to put the zoom area below the plot and finally (if desired) by adding theme(zoom.y = element_rect(fill = NA)) to get rid of the fill indicating the zoom on the y axis:

    library(ggplot2)
    library(ggforce)
    
    ggplot(data = Dati, aes(x = `cat`, y = `vix`)) +
      geom_point(aes(color = "red"), shape = 1, size = 3.0, stroke = 1.5) +
      scale_color_manual(values = c("#f92410", "#644196")) +
      geom_smooth(level = 0.95, span = 0.8) +
      theme(legend.position = "null") +
      geom_vline(xintercept = 0.2, linetype = "dashed", color = "red") +
      facet_zoom(xlim = c(0.05, 0.2), ylim = c(0, 80), horizontal = FALSE) +
      theme(zoom.y = element_rect(fill = NA))
    

    enter image description here