hal*_*ass 16 r legend ggplot2 geom-text
与此问题类似,我想更改图例中的默认"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))
Run Code Online (Sandbox Code Playgroud)
use*_*650 17
您可以更改图例键生成功能.这仍然需要一些人工干预,但可以说比使用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
Run Code Online (Sandbox Code Playgroud)
您可以按如下方式处理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)
Run Code Online (Sandbox Code Playgroud)