【问题标题】:How to change legend shapes when using geom_sf?使用 geom_sf 时如何更改图例形状?
【发布时间】:2019-12-10 15:19:51
【问题描述】:

我正在使用geom_sfggplot 绘制点,并且想更改点的形状。我可以在地图上更改它们,但图例从不反映点的形状,即使使用override.aes

我不知道是我遗漏了什么还是这是一个错误。我在 Tidyverse 问题跟踪器中追踪了类似的问题,this one 非常相似。但是"resolved" 的问题似乎都没有解决我的问题。

这是一个示例,显示了ggplot 如何无法将形状传播到图例。

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))))

我希望图例条目具有与地图相同的形状,但我得到的是空方块。

【问题讨论】:

  • 运行您的确切代码:Error: stat_sf requires the following missing aesthetics: geometry - 特殊。我添加了 aes(geometry = geometry) 并且它有效。耸肩
  • 您指向的 github 线程似乎是正确的。看起来这是geom_sf 的未解决问题。我认为要走的路要么不手动指定scale_shape,而是使用@markhogue的解决方案,或者,如果你真的想根据自己的喜好塑造点,使用另一个函数/geom来创建你的情节,或者,最简单的hack ,制作一个假图例(制作一个情节并将其与主情节结合使用,例如cowplot或patchwork)

标签: r ggplot2 sf


【解决方案1】:
ggplot() + 
  geom_sf(data = cities, aes(shape = name), show.legend = "point") +
  scale_shape_manual(values = c(1, 2, 3))

【讨论】:

  • 手动更改点的形状时,这不适用于 OP 示例
  • 这对我有用,我添加了theme(legend.key = element_rect(fill = NA)) 以删除灰色背景。
  • 啊,太好了,我没想到:)
猜你喜欢
  • 2018-08-30
  • 2020-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-02
  • 1970-01-01
  • 2020-11-24
  • 1970-01-01
相关资源
最近更新 更多