TransWikia.com

RGB raster plot error in R

Geographic Information Systems Asked on July 30, 2021

I have multiple individual band rasters in tif format, and I tried creating a RGB raster from the R, G, B rasters in R using the raster package and then wrote it to disk. Now, apparently the RGB raster created just fine, as it loaded just fine in ArcMap as seen below. But, now when I try to plot the save RGB raster via raster::plotRGB, I get this error:

Error in (function (classes, fdef, mtable)  : 
  unable to find an inherited method for function ‘plotRGB’ for signature ‘"RasterLayer"’

And with RSToolbox::ggRGB, I get this error:

Error in h(simpleError(msg, call)) : 
  error in evaluating the argument 'x' in selecting a method for function 'sampleRegular': not a valid subset

How can I fix this error? I even get the same error if I the write the raster stack to file and plot that. So, I think I am not writing the raster object to file correctly.

Code

library(raster)
library(RSToolbox)
R = raster("path/Red.tif")
G = raster("path/Green.tif")
B = raster("path/Blue.tif")

RGB = raster::stack(R, G, B)
RGB = raster::brick(RGB)

writeRaster(RGB , filename = "path/RGB.tif",overwrite  = TRUE)

RGB = raster("path/RGB.tif")

plotRGB(RGB) # Gives error

ggRGB(RGB) # Gives error

As shown in ArcMap

enter image description here

Basic raster layer info:

enter image description here

One Answer

In stead of

RGB = raster("path/RGB.tif")

You should do

RGB = brick("path/RGB.tif")

Or even better:

library(terra)
r = rast("path/RGB.tif")
plotRGB(r)

# or
RGB(r) <- 1:3
plot(r) 

Correct answer by Robert Hijmans on July 30, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP