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:
That's all fine and dandy – but how do I get the font family in the legend?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With