R - original colours of georeferenced raster image using ggplot2- and raster-packages

后端 未结 1 1052
深忆病人
深忆病人 2021-01-06 03:52

I would like to use the original colortable of a >>georeferenced raster image<< (tif-file) as coloured scale in a map plotted by

相关标签:
1条回答
  • 2021-01-06 04:51

    Ok, I have found an answer which might not apply to every georeferenced raster image out there, but maybe almost.

    First, my assumption that the data values do bot exactly represent the color selection was wrong. There are 15 unique colors in the colortable of the spatial raster object. However, not all of them are used (14 and 15). Ok, now I know, I have to map my values to the corresponding colors ina way that scale_fill_gradientn understands. For this I am using my previous initial code snippet and define a new variable valTab which stores all unique data values of the given band:

    raster1 <- raster(paste(workingDir, "/HUEK200_Durchlaessigkeit001_proj001.tif", sep="", collapse=""))
    raster1.pts <- rasterToPoints(raster1)
    raster1.df <- data.frame(raster1.pts)
    raster1.img <- melt(raster1)
    colTab <- attr(raster1, "legend")@colortable
    names(colTab) <- 0:(length(colTab) - 1)
    valTab <- sort(unique(raster1.df[[3]]))
    

    Notice, how index names are defined for colTab - this will be important soon. With this, I am able to automatically relate all active colors with their respective value while plotting:

    (ggplot(data=raster1.df)
    + geom_tile(aes(x, y, fill=raster1.df[[3]]))
    + scale_fill_gradientn(colours=colTab[as.character(valTab)])
    + coord_fixed(ratio=1)
    )
    

    Using valTab-members as references to the corresponding color-indices helps to always pick only the colors which are needed. I don't know if defining the values-paramter of scale_fill_gradientn() is necessary in some cases.

    I am not sure if the raster images read by raster() always define their values starting from 0. If not, names(colTab) <- 0:(length(colTab) - 1) needs to be adjusted.

    I hope, this helps somebody in the future. At least, I finally have a solution!

    0 讨论(0)
提交回复
热议问题