从ggplot2 3.2.0开始,可以提供自定义图例绘制功能。因此,如果图例看起来不太正确,您始终可以从 ggplot2 代码库复制相应的图例绘图函数,然后根据需要进行修改。
library(ggplot2)
library(grid)
library(rlang)
# legend drawing function, copied from ggplot2
draw_key_segment_custom <- function(data, params, size) {
if (is.null(data$linetype)) {
data$linetype <- 0
} else {
data$linetype[is.na(data$linetype)] <- 0
}
segmentsGrob(0.1, 0.5, 0.9, 0.5,
gp = gpar(
col = alpha(data$colour %||% data$fill %||% "black", data$alpha),
# the following line was added relative to the ggplot2 code
fill = alpha(data$colour %||% data$fill %||% "black", data$alpha),
lwd = (data$size %||% 0.5) * .pt,
lty = data$linetype %||% 1,
lineend = "butt"
),
arrow = params$arrow
)
}
# sample data
dat <- data.frame(
x = as.factor(1:10),
y = c(20,30,13,37,12,50,31,2,40,30),
z = rep('a', 10)
)
# basic plot
ggplot(dat) +
geom_segment(
aes(x = x, xend = x, y = 0, yend = y+15, linetype = z),
arrow = arrow(length = unit(0.25, 'cm'), type = 'closed'),
size = 0.7,
key_glyph = "segment_custom"
)
Created on 2019-07-25 by the reprex package (v0.3.0)