0

I converted a raster to an image and wanted to plot it. However, I then get the following error:

library(raster)
r
#class      : RasterLayer 
#dimensions : 23320, 37199, 867480680 (nrow, ncol, ncell) 
#resolution : 0.02, 0.02 (x, y) 
#extent     : 341668.9, 342412.9, 5879602, 5880069 (xmin, xmax, ymin, ymax) 
#crs        : +proj=utm +zone=33 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0
#source     : r_tmp_2022-07-21_113344_507_06340.grd 
#names      : layer 
#values     : 2.220446e-16, 0.2999999 (min, max)

x  <- maptools::as.im.Rasterlayer(r)
x
#real-valued pixel image 23320 x 37199 pixel array (ny, nx) 
#enclosing rectangle: [341670, 342410] x [5879600, 5880100] units

plot(x)
#Error in (function (x = seq(0, 1, length.out = nrow(z)), y = seq(0, 1,  :
#‘useRaster = TRUE’ can only be used with a regular grid

I've already tried to find this error with help(plot) or something but there is nothing about it anywhere.

Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63
Maik
  • 1
  • 1
  • Can you provide more context? How do you read the raster in R? What class is it? Some additional code would be really beneficial; i.e showing how you load/convert your file, libraries you are using, etc. – dieghernan Jul 27 '22 at 14:25

1 Answers1

1

In future, please provide a minimal working example - actual data and code that generates the error.

Whenever you get an error, I suggest you immediately type

traceback()

to see the sequence of functions that were executed. (The printout is a traceback: it starts with the function that generated the error, then lists the function that called it, and so on, until it reaches the command line that you originally typed.) This will often tell you where to look.

Since you are plotting an object of class im, and plot is a generic function, the relevant help file is for the method plot.im, i.e. you should type help(plot.im) or ?plot.im, not help(plot).

Since we don't have a working example, we can't debug this for you. But this particular error is probably coming from the R base graphics function image.default and it is apparently complaining that the x and y coordinates in the data do not appear to be equally spaced. You can try either setting useRaster=FALSE in the plot command, or fixing the data.

Some packages alter the x and y coordinates of pixels in an image, by a very small amount, in such a way that other packages "think" the coordinates are not equally spaced. In spatstat there is a function repair.image.xycoords that can be used to repair such data. So, if Z is your image, use

 ZZ <- repair.image.xycoords(Z)

to fix the coordinates, and then plot ZZ.

Adrian Baddeley
  • 2,534
  • 1
  • 5
  • 8