将 geom_text 的默认 "a" 图例更改为标签字符串本身

Change geom_text's default "a" legend to label string itself

this question 类似,我想更改图例中的默认“a”,但我不想将其完全删除,而是想用标签本身替换它。也就是说,图例的第一行应该有一个标有“se”的彩色图标,右边是全名“setosa”。

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

您可以按如下方式处理 grobs:

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

g <- ggplotGrob(p)
lbls <- unique(iris$abbrev)
g$grobs[[15]][[1]][[1]]$grobs[[4]]$label <- lbls[1]
g$grobs[[15]][[1]][[1]]$grobs[[6]]$label <- lbls[2]
g$grobs[[15]][[1]][[1]]$grobs[[8]]$label <- lbls[3]

library(grid)
grid.draw(g)

您可以更改图例键生成函数。这仍然需要一些手动干预,但可以说比使用 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