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

元气小坏坏 提交于 2019-12-21 19:42:26

问题


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


回答1:


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()



来源:https://stackoverflow.com/questions/19289358/how-can-i-plot-a-image-with-x-y-r-g-b-coordinates-using-ggplot2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!