[英]Fitting a quadratic curve in ggplot
This is my sample data. 这是我的样本数据。 I want to plot both
y1
and y2
against x1
in a single plot. 我想在单个图中将
y1
和y2
对x1
进行绘制。 This is what I did: 这就是我做的:
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)
I want to insert a quadratic line for both y1 and y2 against x. 我想为y1和y2插入一条二次线对x。 I did this:
我这样做了:
p + stat_smooth(method = "lm", formula = y ~ x + I(x^2), size = 1)
It throws up an error: 它引发了一个错误:
Warning message:
Computation failed in `stat_smooth()`:
variable lengths differ (found for 'x')
Other than this, the stat_smooth command will only put one quadratic line while I need two quadratic lines for both y1
and y2
. 除此之外,stat_smooth命令只会放置一条二次线,而我需要两条
y1
和y2
二次线。
How did I achieve this in R? 我是如何在R中实现这一目标的?
Thanks 谢谢
You should add two stat_smooth()
calls and add aes()
to show which y
to use. 您应该添加两个
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")
Or make long format table and then you will need just one call of stat_smooth()
and geom_point()
. 或者制作长格式表,然后只需要调用
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.