3

I'm trying to fix up a legend so that there isn't a cross caused by the geom_vline in ggplot. I know my example doesn't make much sense as a plot, but just wanted a quick reproducible example.

library(ggplot2)
ggplot(diamonds)+
  geom_point(aes(x = carat, y = depth, colour = "depth"), pch = 4)+
  geom_line(aes(x = carat, y = table, colour = "table"))+
  geom_vline(aes(xintercept = 2, colour = "x = 2"))+
  guides(colour = guide_legend(override.aes = list(linetype=c(0,1,1), shape=c(4,NA,NA))))

I know I can use guide_legend(override.aes = …) to fix my issue with points and lines both appearing on each legend item but this does not appear to work to remove the vertical line created by geom_vline()

I have found several questions looking for a solution (below) but they all seem to solve it by separating the vline using a different aes (linetype or colours using fill). Is there a way I can keep the colour aes but not have my legend looking like this?

R - combined geom_vline and geom_smooth in legend

Legend showing an unexpected black line with geom_vline

enter image description here

2
  • I'm not sure what you are trying to achieve with the colours. You used aes to map to the depth and table variables, but then you put those variable names in quotes, which does not map to the variables and instead has the effect of giving them a discrete colour.
    – neilfws
    Commented Sep 10, 2018 at 1:00
  • Just want to note that this legend cross issue happens for geom_linerange as well. Setting 'show.legend=F' for geom_linerange and keeping other geom legends visible worked for me too.
    – Jennifer P
    Commented Mar 30, 2020 at 21:44

1 Answer 1

6

This seems to work out for this example. Not sure about your actual data.

library(ggplot2)
ggplot(diamonds)+
  geom_point(aes(x = carat, y = depth, colour = "depth"), pch = 4)+
  geom_line(aes(x = carat, y = table, colour = "table"))+
  geom_vline(aes(xintercept = 2, colour = "x = 2"), show.legend = F)+
  guides(colour = guide_legend(override.aes = list(linetype=c(0,1,1), shape=c(4,NA,NA))))

Created on 2018-09-09 by the reprex package (v0.2.0).

2
  • Perfect! I definitely thought if I set show.legend to FALSE that it wouldn't appear in the legend at all, slightly weird terminology there I think, but good to know. Thank you.
    – Sarah
    Commented Sep 10, 2018 at 1:37
  • I honestly would have thought the same. I just gave it a shot and it looked good.
    – AndS.
    Commented Sep 10, 2018 at 1:40

Not the answer you're looking for? Browse other questions tagged or ask your own question.