感谢 @starja 的提示,
draw_key_point2 <- function (data, params, size) {
`%||%` <- ggplot2:::`%||%`
if (is.null(data$shape)) {
data$shape <- 19
}
else if (is.character(data$shape)) {
data$shape <- ggplot2:::translate_shape_string(data$shape)
}
stroke_size <- data$stroke %||% 0.5
stroke_size[is.na(stroke_size)] <- 0
grid::pointsGrob(0.5, 0.9, pch = data$shape,
gp = grid::gpar(col = alpha(data$colour %||% "black", data$alpha),
fill = alpha(data$fill %||% "black", data$alpha),
fontsize = (data$size %||% 1.5) * .pt + stroke_size * .stroke/2,
lwd = stroke_size * .stroke/2))
}
ggplot(mtcars, aes(gear, mpg,
shape = factor(cyl),
linetype = factor(cyl),
color = factor(cyl))) +
geom_point(size = 2, key_glyph = draw_key_point2) +
stat_summary(fun = mean, geom = "line", size = 1)+
theme(legend.key.width = grid::unit(0.5, "inch"))
![ggplot2 with legend points offset a little](https://istack.dev59.com/Yxy0V.webp)
请注意,此函数需要两个未导出的
ggplot2
函数(
`%||%`
和
translate_shape_string
),这将导致此函数(如果添加到软件包中)无法通过R检查。将这些函数的当前版本复制到您的软件包代码中并冻结它们的主体并不难,但需要注意您需要随着ggplot2的更改/错误修复来更新您的软件包。
此函数使用另一组硬编码默认值(
0.5, 0.9
)替换了一个硬编码默认值集合(
0.5, 0.5
)。显然还有其他解决方法,例如返回函数的函数:
draw_key_point3 <- function(...) {
function(data, params, size) {
`%||%` <- ggplot2:::`%||%`
dots <- list(...)
colour <- dots$colour %||% dots$color %||% data$colour %||% "black"
shape <- dots$shape %||% data$shape %||% 19L
alpha <- dots$alpha %||% data$alpha
if (is.character(shape)) {
shape <- ggplot2:::translate_shape_string(shape)
}
stroke_size <- dots$stroke %||% data$stroke %||% 0.5
stroke_size[is.na(stroke_size)] <- 0
grid::pointsGrob(dots$x %||% 0.5, dots$y %||% 0.5, pch = shape,
gp = grid::gpar(col = alpha(colour, alpha),
fill = alpha(dots$fill %||% data$fill %||% "black", alpha),
fontsize = (dots$size %||% data$size %||% 1.5) * .pt + stroke_size * .stroke/2,
lwd = stroke_size * .stroke/2))
}
}
ggplot(mtcars, aes(gear, mpg,
shape = factor(cyl),
linetype = factor(cyl),
color = factor(cyl))) +
geom_point(size = 2, key_glyph = draw_key_point3(x=0.5, y=0.1, shape = 18)) +
stat_summary(fun = mean, geom = "line", size = 1)+
theme(legend.key.width = grid::unit(0.5, "inch"))
在这里,您可以设置任何关键/图例字形组件(x、y、颜色、形状、透明度、填充、大小)。
draw_key_point
,它硬编码了0.5, 0.5
,这表明在 ggplot2 的正常语言中没有办法修改它。 - r2evansgeom_point(size = 2, key_glyph = my_own_draw_key_point)
。 - starjakey_glyph
。具体来说,任何需要修改底层grob的解决方案,虽然可能有效,但是不够优雅,并且已被证明对ggplot2内部工作的更改很脆弱。有其他关于ggplot2问题的答案依赖于更改grob组件,但现在已经不再起作用...所以我认为坚持使用ggplot2本地方法应该是首选(因此不是重复)。谢谢! - r2evans