2017-03-13 3 views
1

Dies sind meine Beispieldaten. Ich möchte sowohl y1 als auch y2 gegen x1 in einem einzigen Diagramm plotten. Das ist, was ich tat:Anpassen einer quadratischen Kurve in ggplot

library(ISLR) 
library(ggplot2) 

y1<-scale(Auto$horsepower,scale = T,center=T) 
y2<-scale(Auto$weight,scale = T,center=T) 
x1<-Auto$mpg 
df<-data.frame(y1,y2,x1) 

p<-ggplot(df,aes(x=x1)) + 
    geom_point(aes(y = y1), shape = 16) + 
    geom_point(aes(y = y2), shape = 2) 

ich eine quadratische Linie sowohl für y1 und y2 gegen x eingefügt werden soll. Ich tat dies:

p + stat_smooth(method = "lm", formula = y ~ x + I(x^2), size = 1) 

Es wirft einen Fehler:

Warning message: 
Computation failed in `stat_smooth()`: 
variable lengths differ (found for 'x') 

Andere als diese, wird der stat_smooth Befehl setzen nur eine quadratische Linie, während ich zwei sowohl quadratische Linien müssen für y1 und y2.

Wie habe ich das in R erreicht?

Dank

Antwort

9

Sie sollten zwei stat_smooth() Anrufe hinzufügen, und fügen Sie aes() die y zu verwenden, zu zeigen.

ggplot(df,aes(x=x1)) + 
     geom_point(aes(y = y1), shape = 16) + 
     geom_point(aes(y = y2), shape = 2) + 
     stat_smooth(aes(y = y1),method = "lm", formula = y ~ x + I(x^2), size = 1) + 
     stat_smooth(aes(y = y2),method = "lm", formula = y ~ x + I(x^2), size = 1, color = "red") 

Oder lange Formattabelle machen und dann werden Sie brauchen nur einen Anruf von stat_smooth() und geom_point().

library(tidyr) 
df_long <- df %>% gather(variable, value, y1:y2) 

ggplot(df_long, aes(x1, value, color = variable)) + 
     geom_point() + 
     stat_smooth(method = "lm", formula = y ~ x + I(x^2), size = 1) 

enter image description here

Verwandte Themen