Search code examples
rggplot2plottidyversescatter-plot

In ggplot2, remove superfluous points from line legend


I have this plot:

library(ggplot2)
ggplot(iris,
       aes(
           x = Petal.Length,
           y = Petal.Width,
           color = Species,
           linetype = Species,
           shape = Species
       )) +
    geom_count(alpha = 0.20) +
    geom_smooth(method = "lm", se = FALSE) + 
    labs(
        color = "Species (Line)",
        linetype = "Species (Line)",
        shape = "Species (Points)"
    )  +
    guides(
        size = "none"
        )
#> `geom_smooth()` using formula = 'y ~ x'

Created on 2023-11-02 with reprex v2.0.2

I am trying to format the legend so that there is a legend that has point shapes (by color also) and a separate legend for linetype (also by color).

What I actually get is a legend just for shapes (with no color) and a legend for linetype that has colored points. I have tried every iteration of legend labelling that I can think of, to no avail.

Question: Keeping everything else the same, how could I get rid of those points in the Species (Line) legend? And how to add color to the shapes?


Solution

  • You'll need to remove the color guide and override the aesthetics of the shape and linetype guide:

    library(ggplot2)
    
    ggplot(iris,
           aes(
             x = Petal.Length,
             y = Petal.Width,
             color = Species,
             linetype = Species,
             shape = Species
           )) +
      geom_count(alpha = 0.20) +
      geom_smooth(method = "lm", se = FALSE) + 
      labs(
        linetype = "Species (Line)",
        shape = "Species (Points)"
      )  +
      guides(
        size = "none",
        color = "none",
        shape = guide_legend(override.aes = list(alpha = 1, 
                                                 color =  scales::hue_pal()(3))),
        linetype = guide_legend(override.aes = list(color =  scales::hue_pal()(3)))
      )
    

    enter image description here

    However, I might humbly suggest that the reason you have this difficulty is that you are mapping the same variable onto multiple aesthetics. This is completely unnecessary for a clear and legible plot - flipping backwards and forwards between two legends to interpret a plot just makes it harder on the reader, not easier. I would recommend getting rid of the chartjunk, perhaps something like:

    library(geomtextpath)
    
    ggplot(iris, aes(x = Petal.Length, y = Petal.Width, group = Species)) +
      geom_count(alpha = 0.3, aes(color = Species)) +
      geom_textsmooth(aes(label = Species), method = "lm", se = FALSE, 
                      vjust = -0.2, size = 6) +
      scale_size_area() +
      guides(size = "none", color = "none") +
      theme_classic(base_size = 20)
    

    enter image description here

    I think this demonstrates the data more clearly.