Search code examples
rplotpngjpeg

Adding a picture to plot in R


I'm trying to add a picture (jpeg,png doesn't care) to a plot which is defined by the layout function. For example:

a<-c(1,2,3,4,5)

b<-c(2,4,8,16,32)

m <- matrix(c(1,1,1,1,2,3,2,3), nrow = 2, ncol = 4)

layout(m); hist(a);boxplot(a~b);plot(b~a)*

Instead of the histogram on position 1 I want to add an image (In my case it's a map)

I don't know how to deal with the jpeg package, maybe you can help me!


Solution

  • You need to read your png or jpeg file through the png and jpeg packages. Then, with the rasterImage function you can draw the image on a plot. Say that your file is myfile.jpeg, you can try this:

    require(jpeg)
    img<-readJPEG("myfile.jpeg")
    #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)
    

    The above code will draw the image between the (2,2) and (4,4) points.