Наконец, я использовал креативное решение @PoGibas, чтобы добавить geom_line
и затем вручную отредактировать guides
.Поскольку эстетику color
использовал другой геом, мне пришлось использовать другую доступную эстетику, и linetype
был хорошим кандидатом.Я принял ответ @PoGibas, но, надеюсь, приведенный ниже код добавляет разнообразие решения:
library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 3.5.3
library(scales) # just for getting the default colors
ggplot(mpg, aes(x = class)) +
geom_bar(aes(fill = drv),
show.legend = FALSE)+
geom_line(aes(y = 0, # y must be provided, so force it to 0 (if forced to NA, it appears in the OY axis)
linetype = drv)) + # can be any unused aesthetic
guides(linetype = guide_legend(override.aes = list(linetype = "solid",
color = scales::hue_pal()(3),
size = 1)))
Итак, мы можем применить тот же принцип, если мы «заставим»'также используйте alpha
эстетику, а затем отредактируйте guides
при необходимости.
ggplot(mpg, aes(x = class)) +
geom_bar(aes(fill = drv),
show.legend = FALSE)+
geom_line(aes(y = 0,
alpha = drv)) +
guides(alpha = guide_legend(override.aes = list(alpha = 1, # 1 is recycled 3 times here, as size is below as well
color = scales::hue_pal()(3),
size = 2)))
#> Warning: Using alpha for a discrete variable is not advised.
Создано в 2019-05-21 представьте пакет (v0.2.1)