如何从ggplot2图例中删除线条美学?

时间:2016-02-04 23:10:58

标签: r ggplot2 legend

我有一个情节,我想为这些点使用不同的颜色,但根据所有点绘制线性回归:

library(ggplot2)

set.seed(1)

df <- data.frame(x=rnorm(100),
                 y=rnorm(100),
                 group=factor(rep(1:2,each=50)))

ggplot(df,aes(x=x,y=y,color=group)) + 
  stat_smooth(aes(group=1), method="lm", fill=NA) +
  geom_point() + theme_bw()

enter image description here

问题在于,当我使用stat_smooth()添加回归线时,它会在图例中添加我不想要的线条。我无法覆盖颜色以从图例中删除线条,因为我需要点的颜色。如何从图例中删除线条但保留点?

1 个答案:

答案 0 :(得分:5)

您需要做的就是将show.legend = FALSE添加到stat_smooth

ggplot(df, aes(x = x, y = y, color = group, group = 1)) + 
    geom_smooth(method = "lm", se = FALSE, show.legend = FALSE) +
    geom_point() + 
    theme_bw()

plot with no lines in legend