ggplot legend with the use of emojis
Asked Answered
T

1

2

I have the below code which produces a pie chart and a legend. Is there a way to get the emoji and the pie chart to be the same corresponding colour, as at the moment the emojis are black. Also I would like the square colour blocks in the legend removed, and the terms male and female to appear next to the correct emoji

library(tidyverse)
library(emojifont)
load.emojifont("OpenSansEmoji.ttf")

gender<-data.frame(`Gender`=c("Male","Female"),
                   `Proportion`=c(45,55), symbol=c("\UF182","\UF183"))

ggplot(gender, aes(x="", Proportion, fill=symbol, label=symbol)) +
  geom_bar(width = 1, stat = "identity")+
  coord_polar("y", start=0)+
  xlab(NULL)+ylab(NULL) +
  theme(legend.text=element_text(family='fontawesome-webfont'))
Tsar answered 31/5, 2022 at 13:17 Comment(0)
R
5

One option to achieve your desired result would be via a custom key glyph function which replaces the default rects used by geom_bar by your symbols:

  1. For the custom draw_key_symbol function I adpated ggplot2::draw_key_text to your use case.
  2. To pick the right symbols I first set up palettes of colors and symbols which assign colors and symbols to genders. The right symbol is then picked based on the fill color via symbols[names(match.arg(data$fill, pal))]
  3. Instead of symbol I map Gender on the fill aes and use scale_fill_manual to set the colors.

Note: While I use the default ggplot2 colors the code below should also work for custom colors for the genders.

library(ggplot2)
library(grid)
library(emojifont)

load.emojifont("OpenSansEmoji.ttf")

gender <- data.frame(
  `Gender` = c("Male", "Female"),
  `Proportion` = c(45, 55),
  symbol = c("\UF182", "\UF183")
)

# Color palette
pal <- scales::hue_pal()(2)
names(pal) <- c("Female", "Male")
# Symbol palette
symbols <- c("\UF182", "\UF183")
names(symbols) <- c("Female", "Male")

draw_key_symbol <- function(data, params, size) {
  data$label <- symbols[names(match.arg(data$fill, pal))]
  
  grid::textGrob(data$label, 0.5, 0.5, 
                 gp = grid::gpar(col = data$fill, 
                                 fontfamily = "fontawesome-webfont", 
                                 fontsize = 3.88 * .pt))
}

ggplot(gender, aes(x = "", Proportion, fill = Gender)) +
  geom_bar(width = 1, stat = "identity", key_glyph = "symbol") +
  scale_fill_manual(values = pal) +
  coord_polar("y", start = 0) +
  labs(x = NULL, y = NULL)

enter image description here

Refuse answered 31/5, 2022 at 14:9 Comment(1)
Great answer, thank youTsar

© 2022 - 2024 — McMap. All rights reserved.