How to add legend with glyphs to a ggplot map

Viewed 43

I am creating a map with ggplot in R. The map contains shapefiles (lines and points) of the sf class, for which I would like to create a legend, but I can’t figure out how to do it. The legend should include the glyph of the point shapefile in the corresponding color(red square) and line for the line shapefile in the corresponding color (black line), and title what it shows (red square is "discovery" and black line is "path"). Can anybody help?

Please see my code here:

ggplot(data = SF_NP_boundary)+
  geom_sf(fill = "antiquewhite1")+
  geom_sf(data = SF_PATROL_ROUTE, size = 0.1, fill = "black") +
  geom_sf(data = SF_PRESENCES, size = 4, 
          shape = 23, fill = "red") +
  theme(panel.grid.major = element_line(colour = gray(0.2), linetype = "dashed", 
                                        size = 0.1), panel.background = element_rect(fill="aliceblue"), 
        panel.border = element_rect(fill = NA))+
  annotation_scale(location = "bl", width_hint = 0.5, height = unit(0.15, "cm"), pad_y = unit(0.15, "in")) +
  annotation_north_arrow(location = "bl", which_north = "true", 
                         pad_x = unit(0.1, "in"), pad_y = unit(0.35, "in"),
                         style = north_arrow_fancy_orienteering)
1 Answers

It looks like you're new to SO; welcome to the community! If you want great answers quickly, it's best to make your question reproducible. This includes sample data like the output from dput() and any libraries you are using. Check it out: making R reproducible questions.

Since your question isn't reproducible, I used different data. This should point you in the right direction, though.

library(tidyverse)
library(sf)
nc = st_read(system.file("shape/nc.shp", package="sf"), quiet = TRUE)

Then added data to have discrete color variation (since that's what you have in yours). You won't have to do anything like this with your data, but I wanted my answer to be reproducible.

nc$what <- rep("A", nrow(nc))
set.seed(33)
nc$what[sample(1:100, 70)] <- NA

In the graph, I added two things. For each layer you want in your legend, you'll add the parameter show.legend. If you wanted the lines, use "line." For a polygon, use "polygon." You can read more about this in help for geom_sf().

I also added scale_fill_manual, because you need to add the labels you want shown in the legend. I added a few things so you could see how it landed in the plot.

ggplot(nc) + geom_sf(fill = "gray") +
  geom_sf(data = na.omit(nc), show.legend = "polygon", fill = "red") +
  scale_fill_manual(values = c("Affected Counties" = "red"), name = "Legend")

enter image description here

Related