1

I wanted to make a simple plot of four sf-objects which don't contain much more than the sfc-column and some postal-code information.

The sf-objects have the names level 1-4 and plz. What I would like to have is a simple legend next to my map just showing the names of the objects (level 1-4) and plz and their matching colours.

It seems like a task which would be so easy in any desktop-gis, but I'd really like to do it in R. My code so far looks like this and produced the follwing figure.

ggplot() +
  geom_sf(data = level3, fill = fil.a) +
  geom_sf(data = level2, fill = fil.b) +
  geom_sf(data = level1, fill = fil.c) +
  geom_sf(data = plz, fill = "red") +
  coord_sf()

enter image description here

1 Answer 1

3

you have to pass the parameter "show.legend = 'polygon'" to geom_sf(); since you are not "mapping" a variable to the polygon's fill, but using 4 geom_sf() calls, you have to adjust scale_fill_manual to refer to the colors and polygons, first referring them on the geom_sf call:

geom_sf(data = level3, aes(fill = "A"), alpha = .5, 
          show.legend = "polygon", inherit.aes = F) +
geom_sf(data = level2, aes(fill = "B"), alpha = .5, 
          show.legend = "polygon", inherit.aes = F) +
scale_fill_manual(values = c("A" = "red", "B" = "green"), 
                    labels = c("level3", "level2"), name = "the_levels")
4
  • 1
    thanks a lot!! I'll give it a shot tomorrow!
    – Lenn
    Commented Nov 21, 2019 at 22:35
  • thanks a lot:) It worked pretty good. But do you have any idea, how I could add another layer with the legend-label depending on one of the column-names. In this case the plz-layer has a column labeled plz. And I would like to add "plz" to my legend.
    – Lenn
    Commented Nov 22, 2019 at 8:57
  • the way ggplot works is mapping variables to geoms, if you want to see a legend with plz values you should map it to aes(fill = plz), it may be good if you convert it to character or factor (i'm guessing it's postleitzahl), otherwise ggplot will use a continuous scale with min and max values
    – Elio Diaz
    Commented Nov 22, 2019 at 16:04
  • 1
    thanks a lot! Helped a lot again. I hope in some time I can also give some helpful advices here
    – Lenn
    Commented Nov 23, 2019 at 7:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.