在绘制具有多个aes设置的构面时,从ggplot中的图例中删除元素

时间:2015-09-27 09:29:29

标签: r ggplot2 scatter-plot facet legend-properties

我正在使用下面的代码生成一个简单的图表:

# 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

如何从图例中删除线条?我对传奇只显示相应颜色的点而不是geom_smooth(method = "lm", se = FALSE)

的行感兴趣

我查看了Turning off some legends in a ggplot上的问题,然而,在阅读之后,我不清楚如何禁用与特定geom相关的图例元素。

1 个答案:

答案 0 :(得分: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 = FALSE,正如scoa指出的那样,我实际上更喜欢它:

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()