0

I would be grateful if someone could tell me how to modify the legend in the following plot:

  point_data <- data.frame(x = rnorm(10),
                           y = rnorm(10),
                           type=c(rep("A",5),rep("B",5)))

  line_data <- data.frame(x=c(-1,0),
                          y=c(1,0))

  ggplot(data=point_data,
         aes(x=x,
             y=y,
             colour=type)) +
    geom_point(size=0.75) +
    geom_line(data=line_data, 
              aes(x=x,y=y,colour="myline"))

enter image description here

I want to remove "myline" from the legend, and have only points next to "A" and "B".

slabofguinness
  • 773
  • 1
  • 9
  • 19
  • 2
    Do you still want the third box in the legend but with just a line in it and no label or are you looking for a two box legend? – aosmith Apr 02 '19 at 18:07
  • I would like a two box legend please. – slabofguinness Apr 02 '19 at 18:28
  • 1
    Using geom_line(data=line_data, aes(x=x,y=y,colour="myline"),show.legend = FALSE) just removed the line from all three boxes in the legend. I find this counter intuitive, why does a call to geom_line() influence all of the items in the legend? – slabofguinness Apr 02 '19 at 18:29

1 Answers1

1

I would move data and aes() to the geom_pointand remove the color= from geom_line then you will have only "A" and "B" in the legend

ggplot() +
  geom_point(data=point_data, aes(x=x,
                 y=y,
                 color=type), size=0.75) +
  geom_line(data=line_data, 
            aes(x=x,y=y))
domaeg
  • 431
  • 2
  • 6
  • Thanks. Could you explain why that works please? How could I specify the colour of the line in this case without adding it to the legend? – slabofguinness Apr 02 '19 at 18:31
  • @slabofguinness If you still want to set the line color to a constant you can do so outside of `aes()` in `geom_line()`. Like `color = "blue"`. – aosmith Apr 02 '19 at 18:38