Reputation: 571
Is there a way to insert an image into a plot into R and set its color when I do so? I'd like to insert a silhouette for a given data set and set it to match the color I've chosen for plotting the corresponding the data points. I don't have a strong understanding of how graphics are managed - in computer systems in general, and in R - which may inform the answer to this question.
The code below will insert the image, but I can't figure out a way to change the color.
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,
)
Upvotes: 4
Views: 1519
Reputation: 571
Thank you so much!
Because I was using R color names, I had to do a bit of (ungraceful) color conversion. But your code was exactly what I needed! Thank you!
#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")
Upvotes: 1
Reputation: 121608
i don't understand exactly what do you mean by silhouette here. But for me a raster is a matrix of color. So you can change its color. here a demonstration. I am using, grid.raster
from the grid
package. But it the same thing with rasterImage
here 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)
Upvotes: 3