'horizontal legend in terra R package
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:
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))
Solution 1:[1]
Looking at the terra code in gitHub, I found the solution.
You need to pass the loc and ext arguments through the plg list:
rm(list = ls())
library(terra)
library(RColorBrewer)
f <- system.file("ex/elev.tif", package="terra")
r <- rast(f)
e <- c(5.5, 7.0, 49.35, 49.38)
terra::plot(r, plg = list(ext = e, loc = "bottom"))
# Change color scale, range, ticks
terra::plot(r,
col = brewer.pal(7, "BrBG"), range = c(150, 500),
plg = list(ext = l_ext, loc = "bottom", title = "myvar",
at = c(150, 200, 250, 350, 450, 500)))
Solution 2:[2]
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:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Quinten |





