I would like to use the original colortable
of a >>georeferenced raster image<< (tif-file) as coloured scale in a map plotted by ggplot/ggplot2.
Due to not finding an easier solution, I accessed the colortable
-slot from the legend
-attribute of the loaded raster image (object) raster1
like so:
raster1 <- raster(paste(workingDir, "/HUEK200_Durchlaessigkeit001_proj001.tif", sep="", collapse=""))
raster1.pts <- rasterToPoints(raster1)
raster1.df <- data.frame(raster1.pts)
colTab <- attr(raster1, "legend")@colortable
Ok, so far so good. Now I simply need to apply colortable
as a colored scale to my existing plot:
(ggplot(data=raster1.df)
+ geom_tile(aes(x, y, fill=raster1.df[[3]]))
+ scale_fill_gradientn(values=1:length(colTab), colours=colTab, guide=FALSE)
+ coord_fixed(ratio=1)
)
Unfortunately, this does not work as expected. The resulting image does not show any colors beside white and the typical ggplot-grey which often appears when no custom values are defined. At the moment, I am a little clueless what is actually wrong here. I assumed that the underlying band values stored in raster1.df[[3]]
are indices for the color table. This might be wrong. If it is wrong, then how are the band values connected with the colortable
? And even if my assumption would be right: The parameters which I have given to scale_fill_gradientn()
should still result in a more colorful plot, shouldn't they? I checked out what the unique values are:
sort(unique(raster1.df[[3]]))
This outputs:
[1] 0 1 2 3 4 5 6 7 8 9 10 11 12
Apparently, not all of the 256 members of colortable
are used which reminds me that the color does not always need to reflect the underlying band-data distribution (especially when including multiple bands).
I hope, my last thoughts didn't confuse you about the fact that the objective is quite straight forward.
Thank you for your help!