Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R-将图例添加到回归线的绘图图中_R_Ggplot2_Label_Regression_Legend - Fatal编程技术网

R-将图例添加到回归线的绘图图中

R-将图例添加到回归线的绘图图中,r,ggplot2,label,regression,legend,R,Ggplot2,Label,Regression,Legend,我在R中做了一个多元线性回归,我想在图中添加一个简单的图例(ggplot)。图例应显示带有相应颜色的点和拟合线。到目前为止,它运行良好(没有图例): 如何才能最轻松地在此处添加图例 我尝试了类似问题的解决方案,但没有成功(|) 因此,我附加了我的原始模型,如下所示: ggplot() + geom_point(aes(x = training_set$R.D.Spend, y = training_set$Profit), col = 'p1') + geom

我在R中做了一个多元线性回归,我想在图中添加一个简单的图例(ggplot)。图例应显示带有相应颜色的点和拟合线。到目前为止,它运行良好(没有图例):

如何才能最轻松地在此处添加图例

我尝试了类似问题的解决方案,但没有成功(|)

因此,我附加了我的原始模型,如下所示:

ggplot() +
  geom_point(aes(x = training_set$R.D.Spend, y = training_set$Profit),
             col = 'p1') +
  geom_line(aes(x = training_set$R.D.Spend, y = predict(regressor, newdata = training_set)),
            col = 'p2') +
  geom_line(aes(x = training_set$R.D.Spend, y = predict(regressor_sig, newdata = training_set)),
            col = 'p3') +
  scale_color_manual(
    name='My lines',
    values=c('blue', 'orangered', 'green')) +
  ggtitle('Multiple Linear Regression (Training set)') +
  xlab('R.D.Spend [k$]') + 
  ylab('Profit of Venture [k$]')

但这里我得到了“未知颜色名称:p1”的错误。这有点道理,因为我没有在上面定义p1。如何使ggplot识别我的预期图例?

col
移动到
aes
中,然后您可以使用
scale\u color\u manual
设置颜色:

library(ggplot2)
set.seed(1)
x <- 1:30
y <- rnorm(30) + x

fit <- lm(y ~ x)
ggplot2::ggplot(data.frame(x, y)) + 
  geom_point(aes(x = x, y = y)) + 
  geom_line(aes(x = x, y = predict(fit), col = "Regression")) + 
  scale_color_manual(name = "My Lines",
                     values = c("blue"))
库(ggplot2)
种子(1)

x颜色声明必须在
aes()
中,例如
aes(x=training\u set$R.D.Spend,y=training\u set$Profit,color=“p1”)
Ahhh是的,这是有道理的,谢谢@DaveArmstrong-我确实花了几个小时尝试了很多不同的事情,但没有意识到这是在错误的偏执中()
如何定义哪个颜色表示哪个图例?现在,它似乎将geom()方法的相反顺序作为默认顺序。使用2或3行也可以,但不可能使用更多行(例如10行)进行跟踪。它应该按照颜色美学中标签的字母顺序排列。非常感谢@LMc-我将尝试下一步将每个geom()的行链接到图例-这样颜色将自动匹配。
library(ggplot2)
set.seed(1)
x <- 1:30
y <- rnorm(30) + x

fit <- lm(y ~ x)
ggplot2::ggplot(data.frame(x, y)) + 
  geom_point(aes(x = x, y = y)) + 
  geom_line(aes(x = x, y = predict(fit), col = "Regression")) + 
  scale_color_manual(name = "My Lines",
                     values = c("blue"))