简体   繁体   中英

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

在此处输入图片说明

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.

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

在此处输入图片说明

[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   

在此处输入图片说明

Nice solution by cuttlefish! The key is xpd = TRUE (Allows to plot outside plot area) Since I have typed, here it is...

dev.off()
par(mfrow = c(1,2))
par(xpd=TRUE)
plot(1:5, 5:1)
lines(x=-1:2,y=-2:1,col="red")
lines(x=-1:1,y=-1:1,col="red")
lines(x= 1:3,y= 4:2,col="red")
lines(x= 4:7,y= 5:8,col="red")
lines(x= 2:4,y= 5:7,col="red")
# Control the length & slope of lines
plot(1:5, 5:1)
lines(x= -1:1,y=2:4,col="red")
lines(x=rep(1,3),y=0:2,col="red")
lines(x= 1:3,y=rep(6,3),col="red")
lines(x= 3:6,y= 2:5,col="red")
lines(x=c(4,4.2,4.4),y=4:6,col="red")

红线

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM