1

Possible Duplicate:
Overlay data onto Background image in R

I have seen nice graphics with a photo in the background. So it is possible?

May I ask the experts how to place a photo, JPG, or if necessary other format, in the background of a classical histogram so that the borders touch the X and Y axes?

Thank you.

Community
  • 1
  • 1
Shabana
  • 155
  • 1
  • 6

1 Answers1

1

You can use the rasterImage function to add a raster to an existing graph, it will then be the background for anything added on top of that. See the link in @mplourde's comment for ways to read jpeg or other image formats in that can then be used with rasterImage.

Running par('usr') will give you the current user coordinates to plot from axis to axis or you can use grconvertX and grconvertY to find other sets of coordinates. So for a histogram you could plot the histogram, then use rasterImage to place your image, then use hist again with add=TRUE:

tmp <- rnorm(100)
hist(tmp)
image <- as.raster(matrix(0:1, ncol=5, nrow=3))
tmp2 <- par('usr')
rasterImage(image, tmp2[1], tmp2[3], tmp2[2], tmp2[4])
hist(tmp, add=TRUE, border='red', lwd=3)

However, be very careful that the background image does not distract from the histogram itself, possibly fading your image or adding an alpha channel to make it semitransparent can help.

Greg Snow
  • 48,497
  • 6
  • 83
  • 110
  • That is nice Greg. Should i replace matrix () with myimage.jpg in line 3. Thanks i 'll see also the link in @mplourde's comment to get things working. – Shabana Dec 01 '12 at 17:03
  • You need to import the file, not just give the filename. the link mentioned shows ways to import the files. – Greg Snow Dec 02 '12 at 05:45
  • It works and it looks great. I did not change color or transparency. My photos in green fluorescence and black background, I gave the bars a green color with blue borders. I may just give a darker margin outside the plotting area and draw a black border all around the image. – Shabana Dec 03 '12 at 12:05