Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Legend for geom_text with variable font family

Tags:

r

ggplot2

I'd like to have geom_text() labels take on a font family according to a variable. As per the example on the ggplot2 docs (scroll down to the bottom), I have done this (same as in ggplot docs example):

library(ggplot2)
p <- ggplot(mtcars, aes(x=wt, y=mpg, label=rownames(mtcars)))
p + geom_text(aes(family=c("serif", "mono")[am+1]))

Yielding:

enter image description here

That's all fine and dandy – but how do I get the font family in the legend?

like image 335
maxheld Avatar asked Feb 12 '15 20:02

maxheld


1 Answers

Its not pretty: You can change the font family of the legend labels at the grob level (i dont know another way, but i expect there is).

First add colour to the aesthetic so that a legend is automatically produced, then set the colours manually, with scale_colour_manual to keep them as before. Then tweak the legend details, to change the labels and fonts in the key.

library(ggplot2)
library(grid)



p <- ggplot(mtcars, aes(x=wt, y=mpg, colour=factor(am), label=rownames(mtcars))) + 
         geom_text(aes(family=c("serif", "mono")[am+1])) + 
         scale_colour_manual(values=c('0'= "#000000FF", '1'="#000000FF"),
                             name="am") +
         theme(legend.text=element_text(size=16),
               legend.key.width=unit(2, "cm"))

g <- ggplotGrob(p)

# change labels and fonts
g$grobs[[8]]$grobs[[1]]$grobs[[4]]$label <- "mono"
g$grobs[[8]]$grobs[[1]]$grobs[[4]]$gp$fontfamily <- "mono"
g$grobs[[8]]$grobs[[1]]$grobs[[6]]$label <- "serif"
g$grobs[[8]]$grobs[[1]]$grobs[[6]]$gp$fontfamily <- "serif"

grid.newpage()
grid.draw(g)

enter image description here

like image 106
user20650 Avatar answered Sep 28 '22 15:09

user20650