Home > Enterprise >  In ggplot2, remove superfluous points from line legend
In ggplot2, remove superfluous points from line legend

Time:11-05

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 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.

CodePudding user response:

Depending on your use-case, another potential option is to add a new color scale using the ggnewscale package, e.g.

library(ggplot2)
library(ggnewscale)

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

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

  • Related