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.

4

1 回答 1

3

诀窍是覆盖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() 

出于某种原因,theme_pander对我来说看起来不同。

更新:或者,您可以使用show.legend = FALSEscoa 指出的,我实际上更喜欢:

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() 
于 2015-09-27T09:46:54.823 回答