Ggplot geom_point: how to set a font for custom graphic characters?

With ggplot::geom_pointwe can set any character to build characters with scale_shape_manual. I give an example that demonstrates the goal: use triangles to create a heat map with two values ​​in each cell:

require(ggplot2)

data <- data.frame(
    val = rnorm(40),
    grp = c(rep('a', 20), rep('b', 20)),
    x   = rep(letters[1:4], 5),
    y   = rep(letters[1:5], 4)
)

p <- ggplot(data, aes(x = x, y = y, color = val, shape = grp)) +
    geom_point(size = 18) +
    scale_shape_manual(values=c("\u25E4","\u25E2")) +
    theme_minimal() +
    theme(panel.grid = element_blank())

ggsave('triangle-tiles.pdf', device = cairo_pdf, width = 4.1, height = 3.5)

triangle heatmap with geom_point

This works great if the font used for characters has these special characters. Otherwise, it seems to fail. I know that we can explicitly define the font and get the same result with geom_text:

require(dplyr)

data <- data %>% mutate(sym = ifelse(grp == 'a', "\u25E4", "\u25E2"))

p <- ggplot(data, aes(x = x, y = y, color = val, label = sym)) +
    geom_text(size = 18, family = 'DejaVu Sans') +
    theme_minimal() +
    theme(
        panel.grid = element_blank()
    )

ggsave('triangle-tiles-2.pdf', device = cairo_pdf, width = 4.1, height = 3.5)

However, the fact that also in geom_pointare characters emanating from the font makes me really curious how to overwrite the default.

, :

gr <- ggplotGrob(p)
gr[['grobs']][[6]]$children$geom_point

x, y, size, lwd ( ) .., . , , . grid::getGrob, . grid::grid.edit .

, editGtable, , , , , editGrob :

font <- gpar(fontfamily = 'DejaVu Sans', fontsize = 14)
editGrob(gr[['grobs']][[6]], 'geom_point.points', grep = TRUE, global = TRUE, gp = font)
+4

Source: https://habr.com/ru/post/1692942/


All Articles