【问题标题】:How to remove the legend key border in ggplot's geom_sf?如何删除ggplot\'s geom_sf中的图例键边框?
【发布时间】:2022-08-11 23:48:00
【问题描述】:

默认情况下geom_sf 绘制一个图例,其键(填充颜色)被边框颜色的框架包围(即color aesthetic)。有没有办法去掉这个框架?显然,这个框架是里面关键矩形,因此不能通过在下面的示例中修改 legend.key 来覆盖它。

library(tidyverse)
library(sf)
library(spData)

spData::world %>% 
  ggplot(aes(fill = continent)) +
  geom_sf() +
  theme(legend.key = element_rect(colour = \"red\"))

由reprex package (v2.0.1) 于 2022 年 8 月 11 日创建

理想情况下,我不仅会删除框架,还会完全删除图例键之间的垂直空间,类似于guide_colorsteps 的外观。

我在这里的 hacky 尝试成功地移除了框架,但矩形还不是完全相邻的。是否有 a) 一种不那么笨拙的方法来移除框架,以及 b) 一种方法来完全移除矩形之间的垂直空间?

library(tidyverse)
library(sf)
library(spData)

spData::world %>% 
  ggplot() +
  geom_sf(aes(fill = continent, color = continent)) +
  geom_sf(data = st_geometry(spData::world), fill = NA, color = \"black\") + 
  theme(legend.spacing.y = unit(0, \'cm\')) +
  guides(fill = guide_legend(byrow = TRUE))

由reprex package (v2.0.1) 于 2022 年 8 月 11 日创建

    标签: r ggplot2


    【解决方案1】:

    一种不需要使用theme 或guides 的可能选项是将key_glyph 设置为"rect":

    library(tidyverse)
    library(sf)
    #> Linking to GEOS 3.9.1, GDAL 3.4.3, PROJ 7.2.1; sf_use_s2() is TRUE
    library(spData)
    #> To access larger datasets in this package, install the spDataLarge
    #> package with: `install.packages('spDataLarge',
    #> repos='https://nowosad.github.io/drat/', type='source')`
    
    spData::world %>% 
      ggplot(aes(fill = continent)) +
      geom_sf(key_glyph = "rect", color = "red")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-02
      • 2014-01-30
      • 1970-01-01
      • 1970-01-01
      • 2019-01-30
      • 1970-01-01
      • 2018-11-03
      • 2016-06-07
      相关资源
      最近更新 更多