Last active
November 4, 2021 10:36
-
-
Save teunbrand/3c6cd496b230adfab1d469099c0d1b3c to your computer and use it in GitHub Desktop.
Drawing the keys of a ggplot2 legend from SVG files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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")) |
Author
teunbrand
commented
Nov 4, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment