带有可变字体系列的geom_text的图例 [英] Legend for geom_text with variable font family

查看:63
本文介绍了带有可变字体系列的geom_text的图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让 geom_text()标签根据一个变量使用字体家族.按照 ggplot2文档上的示例(向下滚动至底部),我已经完成了这(与ggplot docs示例相同):

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]))

屈服:

这一切都很好,但我如何在图例中获得字体家族?

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

推荐答案

它并不漂亮:您可以在 grob 级别更改图例标签的字体系列(我不知道另一种方法,但是我希望有).

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).

首先将 colour 添加到外观中,以便自动生成图例,然后使用 scale_colour_manual 手动设置颜色,以使其与以前一样.然后调整图例详细信息,以更改键中的标签和字体.

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)

这篇关于带有可变字体系列的geom_text的图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆