Randall Helms
Randall Helms

Reputation: 859

Using FontAwesome in ggplot2 as a replacement for points

This is probably a fairly basic thing, but I can't seem to find a meaningful answer.

I am trying to use the fontawesome package in R to use emojis as points in a ggplot2 chart, but I am having a hard time figuring out how to assign a different emoji to each variable.

Here's some sample data (we'll call the data frame 'sample'):

sample <- structure(list(month = c(1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 3L, 
4L, 5L, 6L), number = c(456550L, 374616L, 462086L, 436376L, 497526L, 
488574L, 119884L, 126356L, 129338L, 177496L, 128404L, 156754L
), variable = c("var1", "var1", "var1", "var1", "var1", "var1", 
"var2", "var2", "var2", "var2", "var2", "var2")), class = "data.frame", row.names = c(NA, 
-12L))

I've looked at the example code from the package author, however I can't figure out a way to assign a separate emoji to var1 and var2.

Using the FontAwesome cheatsheet, let's say that I wanted var1 to be 'fa-windows' and var2 to be 'fa-linux'. Here's a bit of plot code I worked up from the package author's example:

library(ggplot2)
library(emojifont)
library(scales)

load.fontawesome()
testLabels <- fontawesome(c('fa-windows','fa-linux'))

windows() #only necessary if using RStudio

ggplot(sample,aes(x=month,y=number,color=variable))+
  geom_text(aes(label=testLabels),family='fontawesome-webfont', size=6)+
  scale_y_continuous(labels = comma)+
  theme(legend.text=element_text(family='fontawesome-webfont'))

This throws an error: "Error: Aesthetics must be either length 1 or the same as the data", which is not surprising as I haven't set var1 and var2 to correspond with the relevant FontAwesome values in testLabels anywhere in the code. However, I don't know how to do that, and I can't find the answer online (perhaps my search skills are lacking).

I am sure that users with more ggplot2 experience can help me find the answer quickly - thanks in advance!

Upvotes: 4

Views: 2775

Answers (1)

Guangchuang Yu
Guangchuang Yu

Reputation: 195

labs <- data.frame(variable=c("var1", "var2"),
                   label = fontawesome(c('fa-windows','fa-linux')))
d <- merge(sample, labs, by.x="variable", by.y="variable")
ggplot(d,aes(x=month,y=number,color=variable))+
  geom_text(aes(label=label),family='fontawesome-webfont', size=6)+
  scale_y_continuous(labels = comma)+
  theme(legend.text=element_text(family='fontawesome-webfont'))

never use variable in aes which should only use for aesthetic mapping.

Upvotes: 3

Related Questions