rggplot2unicodeshapesfill

Custom shape in ggplot (geom_point) - use inside fill with unicode (e.g., hearts)


This is a follow-up to this question (part 1): Custom shape in ggplot (geom_point)

Which provided a solution to produce custom ggplot2 shapes in the form of skulls 💀 (or hearts ❤):

library(ggplot2)
df <- read.table(text="x y
                 1    3
                 2    4
                 3    6
                 4    7", header=TRUE) 

ggplot(data = df, aes(x =x, y=y)) +  
  geom_point(shape="\u2764",
             colour = "red",
             fill = "white",
             size = 6)

Created on 2023-12-25 with reprex v2.0.2

Very nice. But a problem arises that I have specified a white fill but the inside is still transparent. How can I fill it white?


Solution

  • With geom_text() you'd have more control over used fonts (e.g. using Font Awesome for icons); and with 2 geom_text() layers, you could first draw solid (white) hearts and then add regular glyphs to add red outline. If using AGG graphics device (ragg package, Tools / Global Options / General / Graphics setting in RStudio, ragg_png device for knitr) is an option, systemfonts-based solution might look like something like this:

    library(ggplot2)
    library(systemfonts)
    
    # otfs folder from FA6 free desktop download, https://fontawesome.com/download
    fs::dir_tree("otfs")
    #> otfs
    #> ├── Font Awesome 6 Brands-Regular-400.otf
    #> ├── Font Awesome 6 Free-Regular-400.otf
    #> └── Font Awesome 6 Free-Solid-900.otf
    
    # register Font Awesome regular and solid fonts from local path
    register_font("fa-regular", "otfs/Font Awesome 6 Free-Regular-400.otf")
    register_font("fa-solid",   "otfs/Font Awesome 6 Free-Solid-900.otf")
    
    df <- read.table(text="x y
                     1    3
                     2    4
                     3    6
                     4    7", header=TRUE) 
    
    ggplot(data = df, aes(x =x, y=y)) +  
      geom_text(label = "heart", family = "fa-solid", colour = "white", size = 6) +
      geom_text(label = "heart", family = "fa-regular", colour = "red", size = 6)
    

    Created on 2023-12-25 with reprex v2.0.2