Skip to content

Instantly share code, notes, and snippets.

@teunbrand
Last active November 4, 2021 10:36
Show Gist options
  • Save teunbrand/3c6cd496b230adfab1d469099c0d1b3c to your computer and use it in GitHub Desktop.
Save teunbrand/3c6cd496b230adfab1d469099c0d1b3c to your computer and use it in GitHub Desktop.
Drawing the keys of a ggplot2 legend from SVG files
# Load libraries
library(ggplot2)
library(grid)
library(rlang)
library(grImport2)
# Replace by intended SVG file
file <- "https://upload.wikimedia.org/wikipedia/commons/d/db/Brain_Drawing.svg"
download.file(file, tmp <- tempfile(fileext = ".svg"))
# Function factory for rendering keys from an SVG file
key_svg <- function(file) {
# Import SVG file as a grob
grob <- readPicture(rawToChar(rsvg::rsvg_svg(file)))
grob <- pictureGrob(grob)
# Key drawing function
function(data, params, size) {
# Determine graphical parameters
gp <- gpar(
col = alpha(data$fill %||% "black", data$alpha),
fill = alpha(data$fill %||% "black", data$alpha),
lwd = (data$stroke %||% data$size %||% 0.5) * .pt,
fontsize = 1
)
# Edit graphical parameters of imported SVG
editGrob(grob, gp = gp, global = TRUE,
gPath = "picComplexPath", grep = TRUE)
}
}
# Plot
ggplot(mpg, aes(displ, hwy, fill = class)) +
geom_point(shape = 21, key_glyph = key_svg(tmp)) +
theme(legend.key.size = unit(1, "cm"))
@teunbrand
Copy link
Author

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment