2

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.

Community
  • 1
  • 1
Konrad
  • 17,740
  • 16
  • 106
  • 167
  • 1
    possible duplicate of [Turning off some legends in a ggplot](http://stackoverflow.com/questions/14604435/turning-off-some-legends-in-a-ggplot) – scoa Sep 27 '15 at 09:48
  • 1
    add `show_guide = FALSE` to `geom_smooth` – scoa Sep 27 '15 at 09:48
  • @scoa `show_guide` is deprecated, but he could use `show.legend = FALSE` instead. That's actually simpler than my answer. – Thomas K Sep 27 '15 at 09:51
  • possible duplicate of [Legend in ggplot2, remove level](http://stackoverflow.com/questions/32780092/legend-in-ggplot2-remove-level) – Jaap Sep 27 '15 at 10:47

1 Answers1

3

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() 
Thomas K
  • 3,242
  • 15
  • 29