簡體   English   中英

在ggplot中擬合二次曲線

[英]Fitting a quadratic curve in ggplot

這是我的樣本數據。 我想在單個圖中將y1y2x1進行繪制。 這就是我做的:

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) 

我想為y1和y2插入一條二次線對x。 我這樣做了:

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

它引發了一個錯誤:

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

除此之外,stat_smooth命令只會放置一條二次線,而我需要兩條y1y2二次線。

我是如何在R中實現這一目標的?

謝謝

您應該添加兩個stat_smooth()調用並添加aes()以顯示要使用的y

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

或者制作長格式表,然后只需要調用stat_smooth()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)

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM