rggplot2geom-hlinegeom-vline

R ggplot: "cross effect" in legend (not going away with show.legend = NA)


The following code causes an unwanted cross effect in the legend.

ggplot() + 
  geom_vline(aes(xintercept=1,colour="vertical"), show.legend = NA) +
  geom_hline(aes(yintercept=1,colour="horizontal"), show.legend = NA)

enter image description here

I read several posts which say that adding show.legend = NA could make this effect go away, but this isn't working in my case.

Edit: To avoid confusing, I don't want the legend to go away! I just want the "cross" in the legend to go away, so it should show items like:

enter image description here

and

enter image description here


Solution

  • I agree that fixing legends up can get tricky. For this example, simply put show.legend = FALSE for the ONE line you do not want.

    library(ggplot2)
    
    ggplot() + 
      geom_vline(aes(xintercept=1,colour="vertical"), show.legend = F) +
      geom_hline(aes(yintercept=1,colour="horizontal"))
    

    Okay here is attempt 2. It is pretty ugly; it crams two legends into one plot. It looks pretty close to what you want.

    library(ggplot2)
    
    p1 <- ggplot() + 
      geom_vline(aes(xintercept=1,colour="vertical"))+
      scale_color_manual(values = "#619CFF")
    
    p2 <- ggplot()+
      geom_hline(aes(yintercept=1,colour="horizontal"))
    
    l1 <- cowplot::get_legend(p1)
    l2 <- cowplot::get_legend(p2)
    
    p3 <- ggplot() + 
      geom_vline(aes(xintercept=1,colour="vertical")) +
      geom_hline(aes(yintercept=1,colour="horizontal"))+
      theme(legend.position = "none")
    
    l3 <- cowplot::plot_grid(l1, l2, ncol = 1, align = "v")
    cowplot::plot_grid(p3, l3, nrow = 1, align = "h", rel_widths = c(1, 0.2))