Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/69.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_Colors_Linear Regression_Legend - Fatal编程技术网

R 向多元线性回归图的单个图添加图例

R 向多元线性回归图的单个图添加图例,r,ggplot2,colors,linear-regression,legend,R,Ggplot2,Colors,Linear Regression,Legend,我在一个绘图中绘制了两个来自两个不同数据集的GGP绘图。曲线图为简单线性回归。我想为不同颜色的图中的线和点添加图例。我该怎么做?我用于绘图的代码如下所示。但是,我没有给它添加一个令人向往的传说 ggplot() + geom_point(aes(x = Time_1, y = value1)) + geom_point(aes(x = Time_2, y = value2)) + geom_line(aes(x = Time_1, y = predict(reg,

我在一个绘图中绘制了两个来自两个不同数据集的GGP绘图。曲线图为简单线性回归。我想为不同颜色的图中的线和点添加图例。我该怎么做?我用于绘图的代码如下所示。但是,我没有给它添加一个令人向往的传说

ggplot() + 
     geom_point(aes(x = Time_1, y = value1)) +
     geom_point(aes(x = Time_2, y = value2)) +
     geom_line(aes(x = Time_1, y = predict(reg, newdata = dataset)))+
     geom_line(aes(x = Time_Month.x, y = predict(regressor, newdata = training_set)))+ 
     ggtitle('Two plots in a single plot')


ggplot2如果在数据中有组,则会自动添加图例。您的原始代码为ggplot()提供了最少的信息量,基本上足以工作,但不足以创建图例

由于两种不同的回归,数据来自两个不同的对象,因此在本例中,似乎只需将'color=“INSERT color NAME”'参数添加到每个geom_point()和每个geom_line()。例如,使用R的内置mtcars数据集,您所拥有的与

ggplot(mtcars) + geom_point(aes(x = cyl, y = mpg)) + geom_point(aes(x = cyl, y = wt)) + ggtitle("Example Graph")

你想要的东西可以通过使用类似

ggplot(mtcars) + geom_point(aes(x = cyl, y = mpg, color = "blue")) + geom_point(aes(x = cyl, y = wt, color = "green")) + ggtitle("Example Graph")

这似乎可以解释为

ggplot() + 
 geom_point(aes(x = Time_1, y = value1, color = "blue")) +
 geom_point(aes(x = Time_2, y = value2, color = "green")) +
 geom_line(aes(x = Time_1, y = predict(reg, newdata = dataset), color = "red"))+
 geom_line(aes(x = Time_Month.x, y = predict(regressor, newdata = training_set), color = "yellow"))+ 
 ggtitle('Two plots in a single plot')

您还可以使用aes()中的大小、形状或alpha参数来区分不同的系列。

我尝试了这个方法,但它没有创建图例,只是使绘图色彩鲜艳。我的肚子里需要一块糖果plot@R_mad听起来您要求在绘图范围内使用图例(与我的示例绘图“带图例的图形”中提供的图例相反)。如果是这种情况,那么请研究使用+theme(),theme()函数中有很多图例参数。@如果您说它根本没有创建图例,即使使用color=参数,那就太疯狂了。然后下一步是提供一部分数据,以便有人可以复制您的确切设置。