Может быть, что-то вроде этого?
p +
# hide legend in actual segment layer
geom_segment(data = outliersabovepmax,
aes(xend = class, y = hwy-1, yend = hwy+1),
arrow = arrow(), show.legend = F)+
# have invisible segment layer that shows legend
geom_segment(data = outliersabovepmax,
aes(xend = class, y = hwy-1, yend = hwy+1, linetype = "Outlier above"),
arrow = arrow(), alpha = 0, show.legend = T) +
# override alpha for linetype legend
guides(linetype = guide_legend(override.aes = list(alpha = 1))) +
coord_cartesian(ylim = c(pmin, pmax))
И если вы хотите изменить раскладку ключа легенды geom_segment
, выможет копаться в базовом коде для GeomSegment
:
library(grid)
GeomSegment2 <- ggproto("GeomSegment2", GeomSegment,
draw_key = function (data, params, size) {
data$linetype[is.na(data$linetype)] <- 0
segmentsGrob(
# vertical instead of horizontal line
0.5, 0.1, 0.5, 0.9, #0.1, 0.5, 0.9, 0.5,
gp = gpar(col = alpha(data$colour, data$alpha),
lwd = data$size * .pt,
lty = data$linetype,
lineend = "butt"),
arrow = params$arrow)
})
geom_segment2 <- function (mapping = NULL, data = NULL, stat = "identity",
position = "identity", ..., arrow = NULL, arrow.fill = NULL,
lineend = "butt", linejoin = "round", na.rm = FALSE,
show.legend = NA, inherit.aes = TRUE) {
layer(data = data, mapping = mapping, stat = stat, geom = GeomSegment2,
position = position, show.legend = show.legend, inherit.aes = inherit.aes,
params = list(arrow = arrow, arrow.fill = arrow.fill,
lineend = lineend, linejoin = linejoin, na.rm = na.rm,
...))
}
Использование:
p +
# hide legend in actual segment layer
geom_segment(data = outliersabovepmax,
aes(xend = class, y = hwy-1, yend = hwy+1),
arrow = arrow(), show.legend = F)+
# have invisible segment layer that shows legend
geom_segment2(data = outliersabovepmax,
aes(xend = class, y = hwy-1, yend = hwy+1, linetype = "Outlier above"),
arrow = arrow(), alpha = 0, show.legend = T) +
# override alpha for linetype legend
guides(linetype = guide_legend(override.aes = list(alpha = 1))) +
coord_cartesian(ylim = c(pmin, pmax))