Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot: legend for emojis in plot

The following code produces a chart with emojis instead of point shapes.enter image description here

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

pal <- c("\U1f337"="blue","\U1f370"="red")
set.seed(124)
xdf <- data_frame(x=rnorm(10),y=rnorm(10),
                  label=rep(c("\U1f337","\U1f370"),5))
xdf %>% ggplot(aes(x=x,y=y,label=label,color=factor(label))) +
  geom_text(family="OpenSansEmoji") +
  scale_color_manual("object",values=pal) +
  guides(color=guide_legend(labels=FALSE)) +
  theme(legend.text=element_text(family="OpenSansEmoji"))

It is easy to see that the legend as informative as it could be. It would be nice to have colored emojis instead of twice the colored letter a, and instead of the black emojis, I would like to have the words tulip and cake.

Can this be accomplished?

like image 593
Erich Neuwirth Avatar asked Jun 12 '26 07:06

Erich Neuwirth


1 Answers

I haven't worked much with emoji fonts before, but does the following work for you?

Data wrangling (I prefer to rename the label column to symbol for convenience, to keep their intended usages separate, but your mileage may vary):

xdf2 <- xdf %>%
  rename(symbol = label) %>%
  mutate(label = ifelse(symbol == "\U0001f337", "tulip", "cake"))

> xdf2
# A tibble: 10 x 4
         x      y symbol       label
     <dbl>  <dbl> <chr>        <chr>
 1 -1.39    0.318 "\U0001f337" tulip
 2  0.0383 -1.42  "\U0001f370" cake 
 3 -0.763  -0.405 "\U0001f337" tulip
 4  0.212   0.995 "\U0001f370" cake 
 5  1.43    0.959 "\U0001f337" tulip
 6  0.744   0.918 "\U0001f370" cake 
 7  0.700  -0.151 "\U0001f337" tulip
 8 -0.229  -1.22  "\U0001f370" cake 
 9  0.197  -0.869 "\U0001f337" tulip
10  1.21   -1.04  "\U0001f370" cake 

Plot:

xdf2 %>%
  ggplot(aes(x = x, y = y, shape = symbol, color = label)) +
  geom_point() +
  scale_shape_identity() +
  scale_color_manual(values = c("tulip" = "blue",
                                "cake" = "red"),
                     guide = guide_legend(
                       override.aes = list(shape = c("\U0001f370",
                                                     "\U0001f337"))
                     ))

plot with emoji symbols

(The actual tulip / cake emojis on my machine look different, for some reason...)

like image 80
Z.Lin Avatar answered Jun 14 '26 06:06

Z.Lin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!