更改geom_text的默认“a”图例标签字符串本身 [英] Change geom_text's default "a" legend to label string itself

查看:206
本文介绍了更改geom_text的默认“a”图例标签字符串本身的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

解决方案

您可以更改图例键生成功能。这仍然需要一些人工干预,但可以说比使用grobs还要少。

  library(ggplot2)
library (网格)

数据(虹膜)
虹膜$ abbrev = substr(虹膜$物种,1,2)

oldK< - GeomText $ draw_key#to稍后保存

#定义新键
#如果您手动添加颜色,然后添加颜色矢量
#而不是`scales :: hue_pal()(length(var)) `
GeomText $ draw_key< - 函数(数据,参数,大小,
var = unique(iris $ abbrev),
cols = scales :: hue_pal()(length(var)) ){

#按照ggplot排序这些字母数字/或者因子水平
txt< - if(is.factor(var))levels(var)else sort(var)
txt< - txt [match(data $ color,cols)]

textGrob(txt,0.5,0.5,
just =center,
gp = gpar (col = alpha(data $ color,data $ alpha),
fontfamily = data $ family,
fontface = data $ fontface,
fontsize = data $ size * .pt))
}

ggplot(data = iris,aes( x = Sepal.Length,y = Sepal.Width,
shape = Species,color = Species))+
geom_text(aes(label = abbrev))


#reset key
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屋!

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