3
votes

I'm trying to use ggplot with several different layers of lines, one using a color legend and the other using a linetype legend. Unfortunately, it seems that both layers show up in both legends, as in the simple example below:

hlines <- data.frame(Hline=c("a", "b"), y=c(-1,1))
vlines <- data.frame(Hline=c("x", "y"), x=c(-1,1))
ggplot() +
    geom_hline(data=hlines,
               aes(color=Hline, yintercept=y, linetype=NA),
               linetype="solid",
               show.legend=TRUE) +
    geom_vline(data=vlines,
               aes(linetype=Hline, xintercept=x, color=NA),
               color="black",
               show.legend=TRUE) +
    scale_color_hue(name="Hline color") +
    scale_linetype(name="Vline ltype") +
    xlim(-3, 3) + ylim(-3, 3)

The code produces this plot:

There are already several similar questions, such but none of the proposed solutions fixes the issue in this example. For example, this question was answered by simply eliminating a geom from all the legends, which is not what I want, while this question seems like it should be a solution to my problem, but my code above already incorporates the answer and I still see the problem. So how I can tell ggplot to keep the vertical lines out of the color legend and the horizontal lines out of the linetype legend in the example above?

1

1 Answers

4
votes

All you need is

ggplot() + 
    geom_hline(data = hlines, 
               aes(color = Hline, yintercept = y)) + 
    geom_vline(data = vlines, 
               aes(linetype = Hline, xintercept = x)) + 
    scale_color_hue(name = "Hline color") + 
    scale_linetype(name = "Vline ltype") + 
    xlim(-3, 3) + ylim(-3, 3)

plot with proper legends

ggplot2 takes its legend specifications from whatever is in aes. If it's outside aes but in the geom_* function, it will get plotted, but not put in the legend.

If you specify show.legend = TRUE, it will override that behavior and plot a legend for everything; you actually want show.legend = NA, which is the default.