Created
March 17, 2022 18:06
-
-
Save krassowski/cc869a402c717f9ab72983026be9f5fc to your computer and use it in GitHub Desktop.
ggplot geom_font_awesome
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
library(ggplot2) | |
source('geom_font_awesome.R') | |
shapes_map = c( | |
setosa = 'car', | |
virginica = 'ban', | |
versicolor = 'star' | |
) | |
( | |
ggplot(iris, aes(Sepal.Width, Petal.Width)) | |
+ geom_font_awesome(aes(shape=Species, fill=Species)) | |
+ scale_shape_manual(values=shapes_map) | |
) |
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
library(ggplot2) | |
library(gridtext) | |
library(grid) | |
library(fontawesome) | |
fa_html = Vectorize(function(icon, fill='black', size=1, export_scale=20, display_scale=10) { | |
fa_png(icon, fill=fill, width=size * export_scale, height=size * export_scale) | |
paste0("<img src='", icon, ".png' width='", size * display_scale, "'>") | |
}) | |
draw_key_fa <- function(data, params, size) { | |
richtext_grob(fa_html( | |
data$shape, | |
size=data$size, | |
fill=data$fill | |
), use_markdown=FALSE) | |
} | |
GeomFontAwesome <- ggproto("GeomFontAwesome", Geom, | |
required_aes = c("x", "y"), | |
non_missing_aes = c("size", "shape", "fill"), | |
default_aes = aes( | |
shape = 'star', fill = "black", size = 1.5, | |
alpha = NA | |
), | |
draw_panel = function(data, panel_params, coord) { | |
coords <- coord$transform(data, panel_params) | |
ggplot2:::ggname("geom_font_awesome", | |
richtext_grob( | |
coords$x, coords$y, | |
text = fa_html( | |
coords$shape, | |
size=coords$size, | |
fill=alpha(coords$fill, coords$alpha) | |
) | |
) | |
) | |
}, | |
draw_key = draw_key_fa | |
) | |
geom_font_awesome <- function(mapping = NULL, data = NULL, | |
stat = "identity", position = "identity", | |
..., | |
na.rm = FALSE, | |
show.legend = NA, | |
inherit.aes = TRUE) { | |
layer( | |
data = data, | |
mapping = mapping, | |
stat = stat, | |
geom = GeomFontAwesome, | |
position = position, | |
show.legend = show.legend, | |
inherit.aes = inherit.aes, | |
params = list( | |
na.rm = na.rm, | |
... | |
) | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment