When drawing maps using ggplot/geom_sf, any layer mapped to an aesthetic is represented in the legend. I am also aware that using show.legend = ...
can be used to force legend representation and to manipulate the symbology used (point, line, polygon). However, when plotting simple objects without the need to further map them to an aesthetic, i.e. using colour/fill to show aditional information, no legend entry is given. This also seems to be the case when using show.legend = TRUE
. I found this question on GitHub: https://github.com/tidyverse/ggplot2/issues/3636 . I am not quite sure, whether the person asking was undestood correctly, but there didn't seem to be a good answer. So, using his code:
library(ggplot2)
library(sf)
nc <- st_read(system.file("shape/nc.shp", package = "sf"))
ggplot(nc) + geom_sf(show.legend = TRUE)
fails to produce a legend. I would like the legend to simply show a line in the same colour as shown in the map and give a name for that layer. I can add a legend, using this workaround:
ggplot() +
geom_sf(aes(fill = "US State borders"), nc, show.legend = "line")
However, this now changes the colour of the plotted layer. Ok, so let's try to specify a colour:
ggplot() +
geom_sf(aes(fill = "US State borders"), nc, fill = "grey", show.legend = "line")
Whoops, lost the legend again, probably because I have now specified fill
twice. Is this really not possible using ggplot/geom_sf?