Search code examples
rggplot2scatter-plotfacetlegend-properties

Removing elements from the legend in ggplot when plotting facets with multiple aes settings


I'm using the code below to generate a simple chart:

# Data and libs
data(mtcars)
reuire(ggplot2); require(ggthemes)

# Chart def
ggplot(mtcars, aes(wt, mpg, colour = as.factor(vs))) +
    geom_point(aes(colour = factor(cyl))) + 
    facet_wrap(~ cyl) +
    guides(colour = guide_legend(title = "Something")) +
    geom_smooth(method = "lm", se = FALSE) +
    theme_pander()

Plot

How can I remove the lines from the legend? I'm interested in legend showing only dots with corresponding colours without the lines derive from the geom_smooth(method = "lm", se = FALSE).


I had a look at the question on Turning off some legends in a ggplot, however, after reading it it wasn't clear to me how to disable the legend elements pertaining to a specific geom.


Solution

  • The trick is to override the aes:

    guides(colour = guide_legend(title = "Something", override.aes = list(linetype = 0)))
    
    # Data and libs
    library(ggplot2)
    library(ggthemes)
    
    # Chart def
    ggplot(mtcars, aes(wt, mpg, colour = as.factor(vs))) +
      geom_point(aes(colour = factor(cyl))) + 
      facet_wrap(~cyl) +
      geom_smooth(method = "lm", se = FALSE) + 
      guides(colour = guide_legend(title = "Something", override.aes = list(linetype = 0))) +
      theme_pander() 
    

    For some reason, theme_pander looks different for me though.

    Update: Alternatively, you could use show.legend = FALSE, as scoa pointed out, which I'd actually prefer:

    ggplot(mtcars, aes(wt, mpg, colour = as.factor(vs))) +
      geom_point(aes(colour = factor(cyl))) + 
      facet_wrap(~cyl) +
      geom_smooth(method = "lm", se = FALSE, show.legend = FALSE) + 
      guides(colour = guide_legend(title = "Something")) +
      theme_pander()