问题描述
这是我的示例数据.我想在单个绘图中同时针对x1
绘制y1
和y2
.这就是我所做的:
This is my sample data. I want to plot both y1
and y2
against x1
in a single plot. 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)
我想针对x插入y1和y2的二次线.我是这样做的:
I want to insert a quadratic line for both y1 and y2 against x. I did this:
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命令将只放置一条二次线,而我需要两条二次线对于y1
和y2
.
Other than this, the stat_smooth command will only put one quadratic line while I need two quadratic linesfor both y1
and y2
.
我如何在R中实现这一目标?
How did I achieve this in R?
谢谢
推荐答案
您应该添加两个stat_smooth()
调用并添加aes()
以显示要使用的y
.
You should add two stat_smooth()
calls and add aes()
to show which y
to use.
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()
.
Or make long format table and then you will need just one call of stat_smooth()
and 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)
这篇关于在ggplot中拟合二次曲线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!