2
votes

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

1
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
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

1 Answers

3
votes

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).