将图例添加到多个线性回归图的单个图中

问题描述 投票:0回答:1

我在一个图中绘制了来自两个不同数据集的两个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')

r ggplot2 colors linear-regression legend
1个回答
0
投票

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

由于由于两个不同的回归,您的数据来自两个不同的对象,所以在这种情况下,您所需要的只是向每个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")

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

您还可以使用aes()内的size,shape或alpha参数来区分不同的序列。

© www.soinside.com 2019 - 2024. All rights reserved.