R 4.0.0 : I am trying to change symbols of legend for a plot in ggplot2, at the moment I have overlapping symbols

Viewed 307

I'm making a plot in ggplot2 with a line and a segment, the symbols for these appear overlapped. I can make it so that their symbols are either both an arrow or both a line using show.legend, but I'd like to make the segment an arrow and the line a line. I tried using override.aes to alter it after looking for a solution. changing the shape doesn't appear to do anything. setting the line to 0 makes everything disappear for that symbol.

plot image

library(tidyverse)

ggplot(NULL, aes(x=0, y=0)) + geom_point(alpha = 0) +
  coord_cartesian(xlim = c(-2.5,2.5),ylim = c(-2.5,2.5)) +
  geom_segment(aes(x=0, xend=1, y=0, yend=-2, color ="Vector a"),  arrow = arrow(length = unit(0.5, "cm")), show.legend  = T) +
  geom_abline(aes(intercept=1, slope=1/2, color = "Line 1"), show.legend  = T) +
  scale_y_continuous(breaks=c(-2:2)) + 
  scale_x_continuous(breaks=c(-2:2)) +
  scale_color_manual(values = c("green", "blue"), guide = guide_legend(override.aes = list(linetype = c(1,1),
  shape = c(1,1)))) +
  labs(

    title = "plot (a) line",
    x = "X Axis",
    y = "Y Axis"
  ) 

Thank you in advance for any advice you have in fixing my problem :).

EDIT: looking around I found out the symbol for either can be changed through key_glyph = draw_key_rect with various other draw_keys_ working. they'll still both display at the same time.

1 Answers

Try this:

library(ggplot2)

ggplot(NULL, aes(x=0, y=0)) + geom_point(alpha = 0) +
  coord_cartesian(xlim = c(-2.5,2.5),ylim = c(-2.5,2.5)) +
  geom_segment(aes(x=0, xend=1, y=0, yend=-2, linetype ="Vector a"),
               colour = "blue",
               arrow = arrow(length = unit(0.5, "cm"))) +
  geom_abline(aes(intercept=1, slope=1/2, color = "Line 1")) +
  scale_y_continuous(breaks=c(-2:2)) + 
  scale_x_continuous(breaks=c(-2:2)) +
  scale_color_manual(values = c("green", "blue")) +
  labs(title = "plot (a) line",
       x = "X Axis",
       y = "Y Axis",
       linetype = NULL,
       colour = "colour")

Commentary

You cannot easily use one aesthetic for two different geom levels in ggplot; so you need to fiddle with the build up of your data and call to ggplot to use different aesthetics to create the legend you want. I can't find an explicit statement to this effect. In Hadley Wickham (2015) ggplot2 Elegant Graphics for Data Analysis it states:

“A legend may need to draw symbols from multiple layers. For example, if you’ve mapped colour to both points and lines, the keys will show both points and lines.”

and

"ggplot2 tries to use the fewest number of legends to accurately convey the aesthetics used in the plot. It does this by combining legends where the same variable is mapped to different aesthetics."

Which goes some way to explaining the issues you were having with your plot.

Created on 2020-05-24 by the reprex package (v0.3.0)

Related