Home > Software design >  Unable to add legend for point shapefile using terra R pakage
Unable to add legend for point shapefile using terra R pakage

Time:06-21

I want to add legend for point shapefile plotted on top of a raster. I am using the following code

library(terra)

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

d <- data.frame(lon=c(6.0,6.1,6.2,6.2), 
                lat = c(49.7,49.8,49.9,49.6),
                Class=c("Yes", "No"))

m <- vect(d, geom=c("lon", "lat"), crs=" proj=longlat  datum=WGS84")

plot(m, add = T, col = c("red", "blue"), legend=TRUE,
     plg=list(legend=c("No", "Yes")))

enter image description here

As you can see from the output that the legend is missing. If I add a legend function like

legend("bottomright", legend=names(table(points$Class)), col=c("red", "blue"))

It adds a legend withou the colours. enter image description here

How can I have the respective colours in the legend?

CodePudding user response:

You need to tell the plot function which layer to use:

plot(m, y="Class", add=T, col=c("red", "blue"), legend="bottomright")
  • Related