Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

plot

r

insets

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?

like image 922
R_User Avatar asked Jun 11 '13 09:06

R_User


People also ask

What does inset mean in R?

The optional inset argument specifies how far the legend is inset from the plot margins. If a single value is given, it is used for both margins; if two values are given, the first is used for x - distance, the second for y -distance.

How do you add points to the same plot in R?

To add new points to an existing plot, use the points() function. The points function has many similar arguments to the plot() function, like x (for the x-coordinates), y (for the y-coordinates), and parameters like col (border color), cex (point size), and pch (symbol type).

What does plot do in Rstudio?

The R plot function allows you to create a plot passing two vectors (of the same length), a dataframe, matrix or even other objects, depending on its class or the input type. We are going to simulate two random normal variables called x and y and use them in almost all the plot examples.


1 Answers

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

like image 76
Vincent Zoonekynd Avatar answered Sep 28 '22 18:09

Vincent Zoonekynd