missng
missng

Reputation: 199

How to change legend shapes when using geom_sf?

I'm plotting points using geom_sf and ggplot, and would like to change the shape of the points. I can change them on the map, but the legend never reflects the shape of the points, even when using override.aes.

I can't tell if I'm missing something or if this is a bug. I've traced similar issues in the Tidyverse issue tracker, and this one is quite similar. But none of the "resolved" issues seem to address my problem.

Here is an example showing how ggplot fails to propagate the shape to the legend.

library(sf)
library(ggplot2)

cities <- tibble::tribble(
  ~ lon,    ~ lat,    ~ name,      ~ pop,
  5.121420, 52.09074, "Utrecht",   311367,
  6.566502, 53.21938, "Groningen", 189991,
  4.895168, 52.37022, "Amsterdam", 779808 
) %>% sf::st_as_sf(coords = c("lon", "lat"), crs = 4326)

lines_sfc <- sf::st_sfc(list(
  sf::st_linestring(rbind(cities$geometry[[1]], cities$geometry[[2]])),
  sf::st_linestring(rbind(cities$geometry[[2]], cities$geometry[[3]]))
))

lines <- sf::st_sf(
  id = 1:2,
  size = c(10,50),
  geometry = lines_sfc,
  crs = 4326
)

ggplot(cities) +
  geom_sf(aes(shape = name))

ggplot(cities) + 
  geom_sf(aes(shape = name)) +
  scale_shape_manual(values = c(1:3),
                     guide = guide_legend(
                       override.aes = list(shape = c(1:3))))

ggplot output

I would expect the legend entries to have the same shapes as the map, but instead I get empty squares.

Upvotes: 3

Views: 2690

Answers (1)

markhogue
markhogue

Reputation: 1179

ggplot() + 
  geom_sf(data = cities, aes(shape = name), show.legend = "point") +
  scale_shape_manual(values = c(1, 2, 3))

enter image description here

Upvotes: 3

Related Questions