Search code examples
rggplot2geor-raster

Reading geo-tiff file using raster() ggplot fails with no error message. What causes this error?


I'm attempting to learn how to import, display, and generally handle geo-tiff files in R-Studio and notebook. When I run the code I get no errors. The plot is not displayed but entering the plot name in the console gives an error. It's as if an error is detected, the plot is still created, but no error is reported either by running the chunks or by running 'knit'.

fimage_plot Error: Discrete value supplied to continuous scale

My code chunk:

rlist <- list.files(tiffTestFldrOrig, pattern="tif$",
                full.names=TRUE)
for(tiff_path_nane in rlist) {
  fimage <- raster(tiff_path_nane)
  fill_col_name = names(fimage)
  fimage_df <- as.data.frame(fimage, xy = TRUE)

  fimage_plot <- ggplot() +
    geom_raster(data = fimage_df, aes(x=x, y=y, 
              fill = fill_col_name)) +
    scale_fill_continuous(type = "gradient") +
    coord_quickmap()

  fimage_plot # no plot displayed, no error
  break() # until error corrected
}

I've tried google, searching on various scale_fill_discete, scale_fill_continous, etc. to no avail.

BTW my x & y data are UTM with the third column 16 bit integer values representing temperatures of a wildfire.


Solution

  • This does not work because in:

    geom_raster(data = fimage_df, aes(x=x, y=y, fill = fill_col_name))
    

    you are using a character variable to specify fill. ggplot does not like that.

    You can either avoid changing the names of fimage and then use

     geom_raster(data = fimage_df, aes(x=x, y=y, fill = layer)) 
    

    as in @Majid reply, or use aes_string to associate the character variable to fill:

     geom_raster(data = fimage_df, aes_string(x="x", y="y", fill = fill_col_name)) 
    

    (Note however that aes_string is soft deprecated: in the future it may stop working and you'll have to use tidy evaluation.)

    HTH