使用ggplot2中的geom_smooth更改绘图的图例

时间:2017-05-24 11:51:01

标签: r ggplot2

我有一个非常简单的问题,我正在努力,即在ggplot2中使用geom_smooth改变情节的图例。

这是我的代码:

p1<-    mtcars$group <- factor(mtcars$vs)
    ggplot(mtcars, aes(x=mpg, y=disp, group=group)) +
      geom_smooth(method=lm, se=FALSE,fullrange=TRUE, show.legend=TRUE,aes(linetype=group), colour="black")

p1

result of p1  

我想做的是更改标签:即:从“组”到“图例”,从“0”到“实验”,“1”到“控制”。我尝试通过添加labs参数并使用scale_fill_discrete:

来做到这一点
p2<-  ggplot(mtcars, aes(x=mpg, y=disp, group=group)) +
        geom_smooth(method=lm, se=FALSE,fullrange=TRUE, show.legend=TRUE,aes(linetype=group), colour="black")+
        labs(linetype="Legend")+
      scale_fill_discrete(labels=c("Experiment", "Control"))
p2

结果会更改图例标题(p2)但仍不会更改标签。有任何想法吗?

编辑:

这解决了问题,感谢快速回复:

ggplot(mtcars, aes(x=mpg, y=disp, group=group)) +
  geom_smooth(method=lm, se=FALSE,fullrange=TRUE, show.legend=TRUE,aes(linetype=group), colour="black")+
  labs(linetype="Legend")+
  scale_linetype_discrete(labels=c("Experiment", "Control"))

我的错误是使用scale_fill_discrete代替scale_linetype_discrete

1 个答案:

答案 0 :(得分:0)

如果你运行这样的代码,你会得到错误吗?

ggplot(mtcars, aes(x=mpg, y=disp, group=group)) +
    geom_smooth(method=lm, se=FALSE,fullrange=TRUE, show.legend=TRUE,aes(linetype=group), colour="black")+
    labs(linetype="Legend")+
    scale_linetype_discrete(labels=c("Experiment", "Control"))

我得到这个情节:

enter image description here

相关问题