Changing Glyph in legend in ggplot2

Introduction

The newest version of ggplot2 3.2.0 gave us the ability to change the glyph in the legend like so

library(ggplot2)

ggplot(economics_long, aes(date, value01, colour = variable)) +
  geom_line(key_glyph = "timeseries")

And they can likewise be specified with the draw_key_* functions as well

ggplot(economics_long, aes(date, value01, colour = variable)) +
  geom_line(key_glyph = draw_key_timeseries)

Showcase

The following is all the available draw_key_* functions in ggplot2. Notice that the dark gray color in dotplot and polygon is a result of a unspecified fill aesthetic. Code to generate these figures can be found at the end of this post.

## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union

Custom glyph key

Since the draw_key_* function just return a grob, you can use spend some time and create your own custom glyphs! Taking inspiration from draw_key_boxplot

draw_key_boxplot
## function (data, params, size) 
## {
##     grobTree(linesGrob(0.5, c(0.1, 0.25)), linesGrob(0.5, c(0.75, 
##         0.9)), rectGrob(height = 0.5, width = 0.75), linesGrob(c(0.125, 
##         0.875), 0.5), gp = gpar(col = data$colour %||% "grey20", 
##         fill = alpha(data$fill %||% "white", data$alpha), lwd = (data$size %||% 
##             0.5) * .pt, lty = data$linetype %||% 1))
## }
## <bytecode: 0x7ff0874a8c08>
## <environment: namespace:ggplot2>

will I try to make a glyph by myself using both points and lines.

library(grid)
library(rlang)
draw_key_smile <- function(data, params, size) {
  grobTree(
    pointsGrob(0.25, 0.75, size = unit(.25, "npc"), pch = 16),
    pointsGrob(0.75, 0.75, size = unit(.25, "npc"), pch = 16),
    linesGrob(c(0.9, 0.87, 0.78, 0.65, 0.5, 0.35, 0.22, 0.13, 0.1), 
              c(0.5, 0.35, 0.22, 0.13, 0.1, 0.13, 0.22, 0.35, 0.5)),
    gp = gpar(
      col = data$colour %||% "grey20",
      fill = alpha(data$fill %||% "white", data$alpha),
      lwd = (data$size %||% 0.5) * .pt,
      lty = data$linetype %||% 1
    )
  )
}

ggplot(economics_long, aes(date, value01, colour = variable)) +
  geom_line(key_glyph = draw_key_smile)

And it looks so happy!

Appendix

library(dplyr)
library(magrittr)
library(ggplot2)
library(grid)

draws <- ls(getNamespace("ggplot2"), pattern = "^draw_key_")

legend_fun <- function(x) {
  ggg <- economics_long %>%
    mutate(variable = factor(variable, labels = paste("Option", LETTERS[1:5]))) %>%
    ggplot(aes(date, value01, colour = variable)) +
  geom_line(key_glyph = get(x)) +
    labs(color = x) 
  
  legend <- cowplot::get_legend(ggg)
  
  grid.newpage()
  grid.draw(legend)
}

purrr::walk(draws[1:12], legend_fun)
p <- ggplot(mtcars, aes(wt, mpg, label = rownames(mtcars))) + 
  geom_text(aes(colour = factor(ceiling(seq_len(nrow(mtcars)) %% 5), labels = paste("Option", LETTERS[1:5])))) +
  labs(color = "draw_key_text")
legend <- cowplot::get_legend(p)

grid.newpage()
grid.draw(legend)
purrr::walk(draws[14:16], legend_fun)

session information


─ Session info ───────────────────────────────────────────────────────────────
 setting  value                       
 version  R version 3.6.0 (2019-04-26)
 os       macOS Mojave 10.14.6        
 system   x86_64, darwin15.6.0        
 ui       X11                         
 language (EN)                        
 collate  en_US.UTF-8                 
 ctype    en_US.UTF-8                 
 tz       America/Los_Angeles         
 date     2020-04-23                  

─ Packages ───────────────────────────────────────────────────────────────────
 ! package     * version date       lib source        
 P assertthat    0.2.1   2019-03-21 [?] CRAN (R 3.6.0)
 P backports     1.1.6   2020-04-05 [?] CRAN (R 3.6.0)
 P blogdown      0.18    2020-03-04 [?] CRAN (R 3.6.0)
 P bookdown      0.18    2020-03-05 [?] CRAN (R 3.6.0)
 P cli           2.0.2   2020-02-28 [?] CRAN (R 3.6.0)
 P clipr         0.7.0   2019-07-23 [?] CRAN (R 3.6.0)
 P colorspace    1.4-1   2019-03-18 [?] CRAN (R 3.6.0)
 P crayon        1.3.4   2017-09-16 [?] CRAN (R 3.6.0)
 P desc          1.2.0   2018-05-01 [?] CRAN (R 3.6.0)
 P details     * 0.2.1   2020-01-12 [?] CRAN (R 3.6.0)
 P digest        0.6.25  2020-02-23 [?] CRAN (R 3.6.0)
 P dplyr       * 0.8.5   2020-03-07 [?] CRAN (R 3.6.0)
 P ellipsis      0.3.0   2019-09-20 [?] CRAN (R 3.6.0)
 P evaluate      0.14    2019-05-28 [?] CRAN (R 3.6.0)
 P fansi         0.4.1   2020-01-08 [?] CRAN (R 3.6.0)
 P ggplot2     * 3.3.0   2020-03-05 [?] CRAN (R 3.6.0)
 P glue          1.4.0   2020-04-03 [?] CRAN (R 3.6.0)
 P gtable        0.3.0   2019-03-25 [?] CRAN (R 3.6.0)
 P htmltools     0.4.0   2019-10-04 [?] CRAN (R 3.6.0)
 P httr          1.4.1   2019-08-05 [?] CRAN (R 3.6.0)
 P knitr       * 1.28    2020-02-06 [?] CRAN (R 3.6.0)
 P lifecycle     0.2.0   2020-03-06 [?] CRAN (R 3.6.0)
 P magrittr    * 1.5     2014-11-22 [?] CRAN (R 3.6.0)
 P munsell       0.5.0   2018-06-12 [?] CRAN (R 3.6.0)
 P pillar        1.4.3   2019-12-20 [?] CRAN (R 3.6.0)
 P pkgconfig     2.0.3   2019-09-22 [?] CRAN (R 3.6.0)
 P png           0.1-7   2013-12-03 [?] CRAN (R 3.6.0)
 P purrr         0.3.3   2019-10-18 [?] CRAN (R 3.6.0)
 P R6            2.4.1   2019-11-12 [?] CRAN (R 3.6.0)
 P Rcpp          1.0.4.6 2020-04-09 [?] CRAN (R 3.6.0)
   renv          0.9.3   2020-02-10 [1] CRAN (R 3.6.0)
 P rlang       * 0.4.5   2020-03-01 [?] CRAN (R 3.6.0)
 P rmarkdown     2.1     2020-01-20 [?] CRAN (R 3.6.0)
 P rprojroot     1.3-2   2018-01-03 [?] CRAN (R 3.6.0)
 P rstudioapi    0.11    2020-02-07 [?] CRAN (R 3.6.0)
 P scales        1.1.0   2019-11-18 [?] CRAN (R 3.6.0)
 P sessioninfo   1.1.1   2018-11-05 [?] CRAN (R 3.6.0)
 P stringi       1.4.6   2020-02-17 [?] CRAN (R 3.6.0)
 P stringr       1.4.0   2019-02-10 [?] CRAN (R 3.6.0)
 P tibble        3.0.1   2020-04-20 [?] CRAN (R 3.6.2)
 P tidyselect    1.0.0   2020-01-27 [?] CRAN (R 3.6.0)
 P vctrs         0.2.4   2020-03-10 [?] CRAN (R 3.6.0)
 P withr         2.1.2   2018-03-15 [?] CRAN (R 3.6.0)
 P xfun          0.13    2020-04-13 [?] CRAN (R 3.6.2)
 P xml2          1.3.0   2020-04-01 [?] CRAN (R 3.6.2)
 P yaml          2.2.1   2020-02-01 [?] CRAN (R 3.6.0)

[1] /Users/emilhvitfeldthansen/Desktop/blogv4/renv/library/R-3.6/x86_64-apple-darwin15.6.0
[2] /private/var/folders/m0/zmxymdmd7ps0q_tbhx0d_26w0000gn/T/Rtmpw7nrsD/renv-system-library

 P ── Loaded and on-disk path mismatch.