krt*_*kmr 2 r scatter-plot ggplot2 lm
我试图使用R中的geom_smooth()覆盖多个趋势线.我目前有这个代码.
ggplot(mtcars2, aes(x=Displacement, y = Variable, color = Variable))
+ geom_point(aes(x=mpg, y = hp, col = "Power"))
+ geom_point(aes(x=mpg, y = drat, col = "Drag Coef."))
Run Code Online (Sandbox Code Playgroud)
(mtcars2是mtcars的标准化形式)
我试图使用geom_smooth(method ='lm')为这两个变量绘制两条趋势线.有任何想法吗?
(额外奖励:如果可能,我还想实现'shape = 1'参数来区分变量.以下方法不起作用)
geom_point(aes(x=mpg, y = hp, col = "Power", shape=2))
Run Code Online (Sandbox Code Playgroud)
更新 我设法做到了这一点.
ggplot(mtcars2, aes(x=Displacement, y = Variable, color = Variable))
+ geom_point(aes(x=disp, y = hp, col = "Power"))
+ geom_point(aes(x=disp, y = mpg, col = "MPG"))
+ geom_smooth(method= 'lm',aes(x=disp, y = hp, col = "Power"))
+ geom_smooth(method= 'lm',aes(x=disp, y = mpg, col = "MPG"))
Run Code Online (Sandbox Code Playgroud)
看起来像这样.
但这是一段丑陋的代码.如果有人能让这段代码看起来更漂亮,那就太棒了.此外,我还没有能够实现'shape = 2'参数.
看起来你正在努力使你的生活变得更加艰难......你可以将其他参数传递到aes()
诸如group
和之中shape
.
我不知道我的标准化是否正确,但这应该足以让你朝着正确的方向前进:
library(ggplot2)
library(reshape2)
#Do some normalization
mtcars$disp_norm <- with(mtcars, (disp - min(disp)) / (max(disp) - min(disp)))
mtcars$hp_norm <- with(mtcars, (hp - min(hp)) / (max(hp) - min(hp)))
mtcars$drat_norm <- with(mtcars, (drat - min(drat)) / (max(drat) - min(drat)))
#Melt into long form
mtcars.m <- melt(mtcars, id.vars = "disp_norm", measure.vars = c("hp_norm", "drat_norm"))
#plot
ggplot(mtcars.m, aes(disp_norm, value, group = variable, colour = variable, shape = variable)) +
geom_point() +
geom_smooth(method = "lm")
Run Code Online (Sandbox Code Playgroud)
产量: