How to set the color of the inserted image in r

Is there a way to insert an image into a graph in R and set its color when I do this? I would like to insert a silhouette for a given dataset and set it according to the color that I have chosen to build the corresponding data points. I don’t have a clear understanding of how graphics are managed - in computer systems in general and in R - which can provide an answer to this question.

The code below inserts an image, but I can’t determine how the color changes.

require(jpeg) thiscolor <- "red" plot(x=c(1, 4), y=c(1, 2), main="test plot", col=thiscolor) thispic <- readJPEG(<insert path for any image here>) rasterImage(thispic, xleft=3, xright=3.5, ytop=2, ybottom=1.8, ) 
+4
source share
2 answers

I do not quite understand what you mean by a silut here. But for me, a raster is a color matrix. This way you can change your color. here is a demo. I am using grid.raster from the grid package. But it's the same with rasterImage

here is an example:

 library(png) library(grid) img <- readPNG(system.file("img", "Rlogo.png", package="png")) ## convert it to a raster, interpolate =F to select only sample of pixels of img img.r <- as.raster(img,interpolate=F) ## Change all the white to a blanck img.r[img.r == "#00000000"] <- 'red' plot.new() grid.raster(img.r) 

enter image description here

+3
source

Thank you very much!

Since I used R color names, I had to do a little (carefree) color conversion. But your code was exactly what I needed! Thanks!

  #convert image to raster thispic.r <- as.raster(thispic) #get the hex color rgbratios <- col2rgb(thiscolor)/255 thiscolorhex <- rgb(red=rgbratios[1], green=rgbratios[2], blue=rgbratios[3]) #convert the non-white part of the image to the hex color thispic.r[thispic.r!="#FFFFFF"] <- thiscolorhex #plot it grid.raster(thispic.r, x=xval, y=yval, just="center") 
+1
source

All Articles