Home > OS >  horizontal legend in terra R package
horizontal legend in terra R package

Time:03-18

With terra I would like to place the legend horizontally below the map. From help it seems that this can be done by either passing a character to legend (e.g. legend = "bottomleft") or by passing a list to plg with arguments from the base-R legend function. However, for me none of these work. Please, see code sample below.

Thanks!

rm(list = ls())
library(terra)

f <- system.file("ex/elev.tif", package="terra") 
r <- rast(f)

terra::plot(r)
terra::plot(r, legend = "bottomleft")
terra::plot(r, plg = list(horiz = TRUE))
terra::plot(r, plg = list(x = 6, y = 49.5, horiz = TRUE))

The resulting map is in all cases as follows:

enter image description here

Edit: by passing an extent to plg, that covers an area outside the plot axis limit, the legend is moved in the right place, but horiz = TRUE still doesn't rotate it:

e <- c(5.6, 6.6, 49.2, 49.3)
terra::plot(r, plg = list(ext = e, horizontal = TRUE), mar = rep(4, 4))

enter image description here

CodePudding user response:

Looking at the enter image description here

enter image description here

CodePudding user response:

You could use the package raster and spplot which gives you the option to plot the legend below the plot. You can use this code:

library(raster)
library(terra)

f <- system.file("ex/elev.tif", package="terra") 
r <- rast(f)
spplot(r, scales = list(draw = TRUE), colorkey = list(space = "bottom"))

Output:

enter image description here

  • Related