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

时间:2020-03-05 15:13:15

标签: r ggplot2 colors linear-regression legend

我在一个图中绘制了来自两个不同数据集的两个ggplots。图是简单的线性回归。我想为图中的线条和点添加不同颜色的图例。我怎样才能做到这一点?我用于绘图的代码如下。但是,我未能在其中添加理想的图例。

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')

1 个答案:

答案 0 :(得分:2)

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

由于由于两个不同的回归,您的数据来自两个不同的对象,因此在这种情况下,您所需要做的就是向每个geom_point()和每个geom_line添加'color =“ INSERT COLOR NAME”'参数()。例如,使用R的内置mtcars数据集,您所拥有的类似于

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

Graph without Legend

您可以通过使用类似于

的方式获得所需的内容。
ggplot(mtcars) + geom_point(aes(x = cyl, y = mpg, color = "blue")) + geom_point(aes(x = cyl, y = wt, color = "green")) + ggtitle("Example Graph")

Graph with Legend

似乎会翻译成

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()内的size,shape或alpha参数来区分不同的序列。