admin管理员组

文章数量:1406937

I'm trying to use RGB and colorizefunctions from terra to create a RGB color gradient on my SpatRaster r, however, I get errors and I don't know how to fix them.

# Generate random point in a data frame
df <- data.frame(lon = rnorm(10000, 5.5), lat = rnorm(10000, 52.5))

# Create SpatRaster
r1 <- rast(nrows=250, ncols=250, xmin=min(df[1]), xmax=max(df[1]), 
           ymin=min(df[2]), ymax=max(df[2]))

# Create SpatRaster from df
r <- rasterize(as.matrix(df[1:2]), r1)
plot(r)

# try to use RGB from terra function to create RGB color on my SpatRaster
RGB(r) <- 1:3
Error: [set.RGB] value(s) are not value layer numbers

# try to use colorize from terra function to create RGB color on my SpatRaster
colorize(r, to="rgb")
Error: [colorize] x has no color table

Then, I'm also trying to use coltab(r) as suggested but unsuccessful,

coltab(r) <- data.frame(value=1:250, col=c("red", "blue"))
colorize(r, to="rgb")
plot(r)

I'm only obtain a red raster.

Any suggestions? Thanks in advance.

I'm trying to use RGB and colorizefunctions from terra to create a RGB color gradient on my SpatRaster r, however, I get errors and I don't know how to fix them.

# Generate random point in a data frame
df <- data.frame(lon = rnorm(10000, 5.5), lat = rnorm(10000, 52.5))

# Create SpatRaster
r1 <- rast(nrows=250, ncols=250, xmin=min(df[1]), xmax=max(df[1]), 
           ymin=min(df[2]), ymax=max(df[2]))

# Create SpatRaster from df
r <- rasterize(as.matrix(df[1:2]), r1)
plot(r)

# try to use RGB from terra function to create RGB color on my SpatRaster
RGB(r) <- 1:3
Error: [set.RGB] value(s) are not value layer numbers

# try to use colorize from terra function to create RGB color on my SpatRaster
colorize(r, to="rgb")
Error: [colorize] x has no color table

Then, I'm also trying to use coltab(r) as suggested https://stackoverflow/a/73833702/15834162 but unsuccessful,

coltab(r) <- data.frame(value=1:250, col=c("red", "blue"))
colorize(r, to="rgb")
plot(r)

I'm only obtain a red raster.

Any suggestions? Thanks in advance.

Share Improve this question asked Mar 4 at 10:07 TristanTristan 4703 silver badges11 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

Example data

library(terra)
r <- rast(nrows=16, ncols=16, xmin=0, xmax=1, ymin=0, ymax=1, vals=1:256)

Add a color table

coltab(r) <- data.frame(ID=1:256, col=rainbow(256))
plot(r)

Now that you have a single-layer raster with a color table you could (but probably shouldn't) create a three-layer RGB raster:

x <- colorize(r, to="rgb")
plot(x[[1:3]])

And now that you have three layers, you could use RGB to set/change the color channels:

RGB(x) <- 3:1

PS: The example data you provided only has a single layer. Hence RGB does not work. And the raster only has a one unique value, so you would not expect multiple colors?

本文标签: rCreate a RedGreenBlue (RGB) color on SpatRaster using terra RGB and colorize functionsStack Overflow