要添加到@Bastien 的答案,您可以手动添加图例。这是一个简单的函数,它将使用 leaflet 和 plotrix 库添加一个连续的图例:
addLegendToSFPlot <- function(values = c(0, 1), labels = c("Low", "High"),
palette = c("blue", "red"), ...){
# Get the axis limits and calculate size
axisLimits <- par()$usr
xLength <- axisLimits[2] - axisLimits[1]
yLength <- axisLimits[4] - axisLimits[3]
# Define the colour palette
colourPalette <- leaflet::colorNumeric(palette, range(values))
# Add the legend
plotrix::color.legend(xl=axisLimits[2] - 0.1*xLength, xr=axisLimits[2],
yb=axisLimits[3], yt=axisLimits[3] + 0.1 * yLength,
legend = labels, rect.col = colourPalette(values),
gradient="y", ...)
}
将上述函数与@Bastien 的代码一起使用:
# Load required libraries
library(sf) # Working spatial data
library(dplyr) # Processing data
library(leaflet) # Has neat colour palette function
library(plotrix) # Adding sf like legend to plot
# Get and set plotting window dimensions
mfrowCurrent <- par()$mfrow
par(mfrow=c(1,2))
# Add sf plot with legend
plot(nc[,1], key.pos = NULL, reset = FALSE)
addLegendToSFPlot(values = c(0, 1),
labels = c("False", "True"),
palette = c("lightseagreen", "orange"))
# Add sf plot with legend
plot(nc[,2], key.pos = NULL, reset = FALSE)
valueRange <- range(nc[, 2, drop = TRUE])
addLegendToSFPlot(values = seq(from = valueRange[1], to = valueRange[2], length.out = 5),
labels = c("Low", "", "Medium", "", "High"),
palette = c("blue", "purple", "red", "yellow"))
# Reset plotting window dimensions
par(mfrow=mfrowCurrent)