2

For some reason ggplot adds a border to the actual points when you use geom_label, but doesn't include a border in the legend. A quick example:

library(tidyverse)

mtcars %>%
  rownames_to_column('car') %>%
  slice(1:10) %>%
  ggplot(aes(cyl, mpg, label = car, col = factor(am))) +
  geom_label() +
  scale_x_continuous(limits = c(2, 10))

enter image description here

I want those little 'a's in the legend to have red and blue borders as well (not a border around the whole legend, for clarity), but I can't figure out how. I've explored using the override.aes option within the guides function, but don't know if it's possible to add a border that way.

Walker Harrison
  • 527
  • 3
  • 12

2 Answers2

3

I think the "default" addition of a box around the legend components might be a feature-request (for ggplot2/issues). Meanwhile, this is a hack that I hope somebody else can replace with a more reasonable version.

Add an empty geom_rect.

mtcars %>%
  rownames_to_column('car') %>%
  slice(1:10) %>%
  ggplot(aes(cyl, mpg, label = car, col = factor(am))) +
  geom_label() +
  scale_x_continuous(limits = c(2, 10)) +
  geom_rect(xmin = NA, xmax = NA, ymin = NA, ymax = NA, fill = NA, na.rm = TRUE)

ggplot2 with boundaries on the legend components

r2evans
  • 141,215
  • 6
  • 77
  • 149
  • yes it's a hack but I'll take it. One thing--if I `override` the default text from 'a' to something else, the box isn't growing along with the text length. i.e. adding `...+ guides(color = guide_legend(override.aes = list(label = c('thisthis', 'thatthat'))))` – Walker Harrison Dec 15 '20 at 03:05
3

AS @r2evans says, now it is hard to do it by simple way.
My answer achieves it with creating & replacing the function, GeomLabel$draw_key.
(NOTE: this answer is based on Change geom_text's default "a" legend to label string itself)

library(tidyverse); library(grid)

oldK <- GeomLabel$draw_key # to save for later

# define new key
# if you manually add colours then add vector of colours 
# instead of `scales::hue_pal()(length(var))`
GeomLabel$draw_key <- function (data, params, size#, 
                                # var=unique(iris$abbrev), 
                                # cols=scales::hue_pal()(length())
                                ) {

  gr <- roundrectGrob(0.5, 0.5, width = 0.9, height = 0.9,
            just = "center",
            gp = gpar(col = data$colour, fill = NA))
  gt <- textGrob("a", 0.5, 0.5,
           just="center",
           gp = gpar(col = alpha(data$colour, data$alpha),
                     fontfamily = data$family,
                     fontface = data$fontface,
                     fontsize = data$size * .pt))
  grobTree(gr, gt)
}

mtcars %>%
  rownames_to_column('car') %>%
  slice(1:10) %>%
  ggplot(aes(cyl, mpg, label = car, col = factor(am))) +
  geom_label() +
  scale_x_continuous(limits = c(2, 10))

# reset key
GeomLabel$draw_key <- oldK

enter image description here

cuttlefish44
  • 6,586
  • 2
  • 17
  • 34