Dave_L
Dave_L

Reputation: 383

Specify fill color of size legend in tmap

Here is a simple example of a tmap where the bubble size is mapped to one attribute of a sf object and the color is mapped to another.

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

The result is:

enter image description here

...which is lovely, but the default fill color for the value legend is the first color chosen for the category legend (here it's green). Is it possible to manually specify the value legend fill color so that visually it becomes completely independent of the categories - for example just have the value legend circles filled with grey?

Upvotes: 2

Views: 709

Answers (1)

Jindra Lacko
Jindra Lacko

Reputation: 8699

Consider filling the shapes.legend.fill argument with a grey color of your choosing; note that for this to work you will have to specify the shapes.legend as well - as demonstrated in this example:

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

shapes instead of bubbles

Upvotes: 2

Related Questions