2016-03-29 13 views
4

ggplot内の異なる滑らかさに凡例を追加する際に問題がありますか?ggplot内のgomplotに凡例を追加するには

library(splines) 
    library(ggplot2) 
    temp <- data.frame(x = rnorm(200, 20, 15), y = rnorm(200, 30, 8)) 

    ggplot(data = temp, aes(x, y)) + geom_point() + 
     geom_smooth(method = 'lm', formula = y ~ bs(x, df=5, intercept = T), col='blue') + 
     geom_smooth(method = 'lm', formula = y ~ ns(x, df=2, intercept = T), col='red') 

私は、赤と青の2つのスプラインを持っています。私はそれらの伝説をどのように追加できますか?

答えて

8

aes()に色を入れて、scale_colour_manual()を追加します。

ggplot(data = temp, aes(x, y)) + geom_point() + 
    geom_smooth(method = 'lm', formula = y ~ bs(x, df=5, intercept = T), aes(colour="A")) + 
    geom_smooth(method = 'lm', formula = y ~ ns(x, df=2, intercept = T), aes(colour="B")) + 
    scale_colour_manual(name="legend", values=c("blue", "red")) 

enter image description here

+0

ありがとう!非常に美しい解決策! –

+0

もちろん、scale_colour_manualのlabelsプロパティを使って、AとBのラベルを変更することができます。 – Sid

関連する問題