Ajay jadhav
Ajay jadhav

Reputation: 163

Show pictures on Plot in R using for loop

I have some images, I want to add those images on plot by defining coordinates.

to add single image on plot, I have this code.

require(jpeg)
img<-readJPEG("C:/Users/dell/Desktop/0.jpg")
#now open a plot window with coordinates
plot(1:10,ty="n")
#specify the position of the image through bottom-left and top-right coords
rasterImage(img,2,2,4,4)

But I want show multiple images in R plot

like this

enter image description here

Thanks in advance

Upvotes: 1

Views: 280

Answers (1)

Rui Barradas
Rui Barradas

Reputation: 76615

Maybe something like the code below will show a way how to do what the question asks for. It is not a full solution, since the actual use case graph coordinates will not be the same.

The obvious trick is to shift the picture

  • vertically by changing only the y coordinates. Add the same amount to both ybottom and ytop to keep the proportions.
  • horizontally by changing only the x coordinates. Add the same amount to both xleft and xright to keep the proportions.

In the case of the figure, the amount added was 3.

library(jpeg)

img <- readJPEG(system.file("img", "Rlogo.jpg", package="jpeg"))

old_par <- par(mar = c(2, 3, 1, 1) + 0.1)

xleft <- 2
ybottom <- 21
xright <- 6
ytop <- 25

plot(seq(0, 60, length.out = 31), 0:30, type = "n")
for(i in 1:17){
  xleft <- xleft + 3
  xright <- xright + 3
  rasterImage(img, xleft, ybottom, xright, ytop)
}
for(i in 1:5){
  ybottom <- ybottom - 3
  ytop <- ytop - 3
  rasterImage(img, xleft, ybottom, xright, ytop)
}
for(i in 1:16){
  xleft <- xleft - 3
  xright <- xright - 3
  rasterImage(img, xleft, ybottom, xright, ytop)
}

par(old_par)

enter image description here

Upvotes: 1

Related Questions