Reputation: 45
I am trying to replicate a plot that I have made in raster
using the new(ish) terra
R package but the alpha
argument in terra::plot
does not seem to work the same way as it does in raster
.
I am trying to use the alpha layer to indicate uncertainty in the base (coloured) layer. Below is some simplified code indicating my problem. Using the raster
package, the alpha layer changes the transparency based on values of each individual pixel. When using terra
this doesn't seem to work.
I think I am using the latest version of terra
(1.3.4), and I am on a Mac (version 15.5.11).
library(terra)
library(raster)
par(mfrow=c(1,2))
plot_cols<-terrain.colors(n=5)
## raster package
raster.template<-raster(xmn=1, xmx=5, ymn=1, ymx=5, nrows=5, ncols=5)
legend.ras.comm<-raster.template
legend.ras.comm[]<-rep(c(5,4,3,2,1), 5)
legend.ras.alpha<-raster.template
legend.ras.alpha[]<-rep(c(0.9,0.7,0.45,0.2,0), 5)
plot(t(legend.ras.comm), col=plot_cols, legend=FALSE, axes=FALSE, box=FALSE, main="Raster package")
plot(t(legend.ras.comm), col="#000000", alpha=legend.ras.alpha, add=TRUE, legend=FALSE)
## terra package
raster.template<-rast(xmin=1, xmax=5, ymin=1, ymax=5, nrows=5, ncols=5)
legend.ras.comm<-raster.template
legend.ras.comm[]<-rep(c(5,4,3,2,1), 5)
legend.ras.alpha<-raster.template
legend.ras.alpha[]<-rep(c(0.9,0.7,0.45,0.2,0), 5)
plot(t(legend.ras.comm), col=plot_cols, legend=FALSE, axes=FALSE, main="Terra package")
plot(t(legend.ras.comm), col="#000000", alpha=legend.ras.alpha, add=TRUE, legend=FALSE, axes=FALSE)
Any help with this would be appreciated.
Upvotes: 2
Views: 668
Reputation: 47491
You can now do this with terra 1.3-22
I get, using your code:
## raster package
library(raster)
legend.ras.comm <- raster(xmn=1, xmx=5, ymn=1, ymx=5, nrows=5, ncols=5, vals=rep(c(5,4,3,2,1), 5))
legend.ras.alpha <- setValues(raster.template, rep(c(0.9,0.7,0.45,0.2,0), 5))
legend.ras.comm <- t(legend.ras.comm)
## terra package
library(terra)
legend.ter.comm <- rast(legend.ras.comm)
legend.ter.alpha <- rast(legend.ras.alpha)
par(mfrow=c(1,2))
plot_cols <- terrain.colors(n=5)
plot(legend.ras.comm, col=plot_cols, legend=FALSE, axes=FALSE, box=FALSE, main="Raster package")
plot(legend.ras.comm, col="#000000", alpha=legend.ras.alpha, add=TRUE, legend=FALSE)
plot(legend.ter.comm, col=plot_cols, legend=FALSE, axes=FALSE, main="Terra package")
plot(legend.ter.comm, col="#000000", alpha=legend.ter.alpha, add=TRUE, legend=FALSE, axes=FALSE)
With terra
you can also use a single value that affects all colors
plot(legend.ter.comm, col=plot_cols, alpha=.75)
Or change the transparency by color. Something like this:
plot_cols_alpha <- terrain.colors(n=5, alpha=seq(.75, 1, .05))
plot(legend.ter.comm, col=plot_cols_alpha)
Upvotes: 3