Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I plot a image with (x,y,r,g,b) coordinates using ggplot2?

I have a data frame image.rgb, into which I have loaded the r,g,b value for each coordinate of an image (using the jpeg and reshape packages). It now looks like:

> head(image.rgb)
   y x         r         g         b
1 -1 1 0.1372549 0.1254902 0.1529412
2 -2 1 0.1372549 0.1176471 0.1411765
3 -3 1 0.1294118 0.1137255 0.1176471
4 -4 1 0.1254902 0.1254902 0.1254902
5 -5 1 0.1254902 0.1176471 0.1294118
6 -6 1 0.1725490 0.1372549 0.1176471

Now I want to plot this 'image' using ggplot2. I can plot a specific 'channel' (red or green or blue) one at a time using:

ggplot(data=image.rgb, aes(
            x=x, y=y,
            col=g) #green for example
       ) + geom_point()

...on the default ggplot2 colour scale

Is there a way to specify that the exact rgb values can be taken from the columns I specify?

Using the plot function in the base package, I can use

with(image.rgb, plot(x, y, col = rgb(r,g,b), asp = 1, pch = "."))

But I'd like to be able to do this using ggplot2

like image 909
user2175594 Avatar asked Oct 10 '13 07:10

user2175594


1 Answers

You must add scale_color_identity in order for colors to be taken "as is" :

ggplot(data=image.rgb, aes(x=x, y=y, col=rgb(r,g,b))) + 
    geom_point() + 
    scale_color_identity()

The sample data you provided give very similar colors, so all the points seem to be black. With geom_tile the different colors are a bit more visible :

ggplot(data=image.rgb, aes(x=x, y=y, fill=rgb(r,g,b))) +
    geom_tile() +
    scale_fill_identity()

enter image description here

like image 74
juba Avatar answered Oct 21 '22 23:10

juba