Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom legend position in terra plot

Tags:

r

terra

I am plotting a raster with terra and I want the legend to show on the right side of the raster bounding box. However, when setting the legend position to "right", the legend ends up being placed inside the raster bounding box instead of outside as in the default case. It follows that the legend will generally cover the raster. I am currently using terra development version 1.8-36, but the same behavior occurred also with previous versions. I attach hereby a minimal working example and the related plot.

library(terra)
r <- rast(system.file("ex/elev.tif", package="terra"))
x <- scale_linear(r, 0, 30)
bks <- c(0,0.4,0.8,1.3,2,4,8,15,30)
colors <- c('#3182BD', '#9ECAE1', '#DEEBF7', '#FEE5D9', '#FCAE91',
            '#FB6A4A', '#DE2D26', '#A50F15')
plot(x, col=colors, box=F, axes=F, breaks=bks, reverse=TRUE,
     plg=list(
       x="right",
       title = "Title",
       title.cex = 1.2,
       cex = 1.2
     ))

enter image description here

like image 568
Laura Roich Avatar asked Oct 16 '25 16:10

Laura Roich


2 Answers

You can set classes/interval legend location with plg=list(x=, y=)

library(terra)
r <- rast(system.file("ex/elev.tif", package="terra"))
plot(r, breaks=5, plg=list(x=6.25, y=50.18, title="Title"))  

enter image description here

like image 57
Robert Hijmans Avatar answered Oct 18 '25 09:10

Robert Hijmans


Perhaps you can create the legend manually:

plot(x, col=colors, box=F, axes=F, breaks=bks, legend=FALSE)

legend(legend=rev(paste(bks[-length(bks)], bks[-1], sep=" - ")),
       fill=rev(colors), bty="n",
       x="right", xpd=TRUE,
       title = "Title", title.cex = 1.2)

enter image description here

like image 45
Edward Avatar answered Oct 18 '25 11:10

Edward



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!