更改 geom_text 的默认“a"图例标记字符串本身 [英] Change geom_text's default "a" legend to label string itself
本文介绍了更改 geom_text 的默认“a"图例标记字符串本身的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
类似于
解决方案
您可以更改图例键生成功能.这仍然需要一些人工干预,但可以说比使用 grob 要少.
库(ggplot2)图书馆(网格)数据(虹膜)iris$abbrev = substr( iris$Species, 1, 2 )oldK <- GeomText$draw_key # 保存以备后用# 定义新键# 如果您手动添加颜色,则添加颜色向量# 而不是`scales::hue_pal()(length(var))`GeomText$draw_key <- 函数(数据、参数、大小、var=unique(iris$abbrev),cols=scales::hue_pal()(length(var))) {# sort as ggplot 按字母数字/或因子水平对这些进行排序txt <- if(is.factor(var)) levels(var) else sort(var)txt <- txt[match(data$colour, cols)]textGrob(txt, 0.5, 0.5,只是=中心",gp = gpar(col = alpha(data$colour, data$alpha),fontfamily = data$family,fontface = data$fontface,字体大小 = 数据$大小 * .pt))}ggplot(data=iris, aes(x=Sepal.Length, y=Sepal.Width,形状=物种,颜色=物种)) +geom_text(aes(label = abbrev))# 重置密钥GeomText$draw_key <- oldK
Similarly to this question, I want to change the default "a" in the legend, but rather than removing it completely, I want to replace it with the labels themselves. That is, the first line of the legend should have a colored icon labeled "se" with the full name "setosa" on the right.
iris$abbrev = substr( iris$Species, 1, 2 )
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width,
shape = Species, colour = Species)) +
geom_text(aes(label = abbrev))
解决方案
You can change the legend key generating function. This still requires a bit of manual intervention, but arguably less than using the grobs.
library(ggplot2)
library(grid)
data(iris)
iris$abbrev = substr( iris$Species, 1, 2 )
oldK <- GeomText$draw_key # to save for later
# define new key
# if you manually add colours then add vector of colours
# instead of `scales::hue_pal()(length(var))`
GeomText$draw_key <- function (data, params, size,
var=unique(iris$abbrev),
cols=scales::hue_pal()(length(var))) {
# sort as ggplot sorts these alphanumerically / or levels of factor
txt <- if(is.factor(var)) levels(var) else sort(var)
txt <- txt[match(data$colour, cols)]
textGrob(txt, 0.5, 0.5,
just="center",
gp = gpar(col = alpha(data$colour, data$alpha),
fontfamily = data$family,
fontface = data$fontface,
fontsize = data$size * .pt))
}
ggplot(data=iris, aes(x=Sepal.Length, y=Sepal.Width,
shape=Species, colour=Species)) +
geom_text(aes(label = abbrev))
# reset key
GeomText$draw_key <- oldK
这篇关于更改 geom_text 的默认“a"图例标记字符串本身的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文