Search code examples
rr-grid

Draw arbitrary lines in margins, R plot with several panels


I have this code

par(mfrow = c(1,2))
plot(1:5, 5:1)

Which makes this plot

enter image description here

I'd like to be able to add random lines all over the plot (see red lines for example). They could be on the plot themselves, inner margins, or outer margins.

  • The line coordinates should not be relative to one of the panels. They should be relative to the entire plot area. Ideally, drawn before or after the plots are drawn.
  • It should be possible for the lines to cross from one plot to another, and from the inner to outer margins.

I do not want to use ggplot2. I have a feeling I need to use grid, but I'm not sure where to start.


Solution

  • It isn't difficult. Adding a new white panel (all over the plots), You can draw the segments you want by xpd = TRUE

    Here is my example;

    set.seed(111)
    random_segments <- data.frame(x0 = runif(5, 0, 2), y0 = runif(5, 0, 2), 
                                 x1 = runif(5, 0, 2), y1 = runif(5, 0, 1))
    
    par(mfrow = c(1,2))
    plot(1:5, 5:1)
    plot(11:20, 20:11)
    par(new = T, mfrow = c(1, 1))
    plot(1, type = "n", axes = F, ann = F)
    with(random_segments, segments(x0, y0, x1, y1, xpd = TRUE))
    

    enter image description here

    [EDITED]

    You can do it with making white panel with corrdinate you want and no margin (you needn't use xpd = TRUE because of no margin).

    set.seed(111)
    random_segments <- data.frame(x0 = runif(5, 0, 1), y0 = runif(5, 0, 1), 
                                 x1 = runif(5, 0, 1), y1 = runif(5, 0, 1))
    
    def_par <- par(no.readonly = TRUE)
    par(mfrow = c(1,2))
    plot(1:5, 5:1)
    plot(11:20, 20:11)
    par(new = T, mfrow = c(1, 1), mar = c(0,0,0,0))
    plot(1, type = "n", axes = F, ann = F, xaxs = "i", yaxs = "i", 
         xlim = c(0, 1), ylim = c(0, 1))
    with(random_segments, segments(x0, y0, x1, y1))
    points(c(0, 0, 1, 1), c(0, 1, 0, 1), col = "red")  # to check coordinate
    par(def_par)  # recover   
    

    enter image description here