How to add an inset (subplot) to "topright" of an R plot?

R_User picture R_User · Jun 11, 2013 · Viewed 14.9k times · Source

I'd like to have an inset within a plot that makes up 25% of the width and height of the plotting area (area where the graphs are).

I tried:

# datasets
d0 <- data.frame(x = rnorm(150, sd=5), y = rnorm(150, sd=5))
d0_inset <- data.frame(x = rnorm(1500, sd=5), y = rnorm(1500, sd=5))

# ranges
xlim <- range(d0$x)
ylim <- range(d0$y)

# plot
plot(d0)

# add inset
par(fig = c(.75, 1, .75, 1), mar=c(0,0,0,0), new=TRUE)
plot(d0_inset, col=2) # inset bottomright

This puts the inset to absolute topright and also uses 25% of the device-width. How can I change it to the coordinates and width of the area where the graphs are?

Answer

Vincent Zoonekynd picture Vincent Zoonekynd · Jun 11, 2013

You can use par("usr") to get the limits of the plot, in user coordinates, and grconvert[XY] to convert them to normalized device coordinates (NDC, between 0 and 1), before using them with par(fig=...).

plot(d0)
u <- par("usr")
v <- c(
  grconvertX(u[1:2], "user", "ndc"),
  grconvertY(u[3:4], "user", "ndc")
)
v <- c( (v[1]+v[2])/2, v[2], (v[3]+v[4])/2, v[4] )
par( fig=v, new=TRUE, mar=c(0,0,0,0) )
plot(d0_inset, axes=FALSE, xlab="", ylab="")
box()

Topright inset