在 tmap 中指定尺寸图例的填充颜色

Specify fill color of size legend in tmap

这是一个简单的 tmap 示例,其中气泡大小映射到 sf 对象的一个​​属性,颜色映射到另一个属性。

library(sf)
library(tmap)
# Make 2 attributes for each of 4 points.
sf.att <- data.frame(value = c(10, 20, 30, 40), category = c("foo", "foo", "bar", "bar"))
# Make a geometry list for 4 points.
p.l <- list(st_point(c(1, 5)), st_point(c(1, 1)), st_point(c(5, 1)), st_point(c(5, 5)))
# Combine into a spatial feature object.
p.sf <- st_sf(sf.att, p.l, crs = 4326)
# Make a bounding box with a small amount of extension.
b.box <- bb(p.sf, ext = 3)
# Make a tmap in plot mode
tmap_mode("plot")
tm_shape(p.sf, bbox = b.box) +
  tm_bubbles(size = "value", scale = 5, col = "category")

结果是:

...这很可爱,但是值图例的默认填充颜色是为类别图例选择的第一种颜色(这里是绿色)。是否可以手动指定值图例填充颜色,以便在视觉上它完全独立于类别 - 例如只将值图例圆圈填充为灰色?

考虑用您选择的灰色填充 shapes.legend.fill 参数;请注意,要使其正常工作,您还必须指定 shapes.legend - 如本例所示:

library(sf)
library(tmap)
# Make 2 attributes for each of 4 points.
sf.att <- data.frame(value = c(10, 20, 30, 40), category = c("foo", "foo", "bar", "bar"))
# Make a geometry list for 4 points.
p.l <- list(st_point(c(1, 5)), st_point(c(1, 1)), st_point(c(5, 1)), st_point(c(5, 5)))
# Combine into a spatial feature object.
p.sf <- st_sf(sf.att, p.l, crs = 4326)
# Make a bounding box with a small amount of extension.
b.box <- tmaptools::bb(p.sf, ext = 3)
# Make a tmap in plot mode
tmap_mode("plot")
tm_shape(p.sf, bbox = b.box) +
  tm_bubbles(size = "value", scale = 5, col = "category",
             palette = c("firebrick","cornflowerblue"),
             shapes.legend = 21,
             shapes.legend.fill = "grey80")