简体   繁体   English

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

[英]Adding legend to a single plot of multiple linear regression plot

I plotted two ggplots from two different datasets in one single plot.我在一个图中绘制了来自两个不同数据集的两个 ggplots。 plots are simple linear regression.图是简单的线性回归。 I want to add legend both for lines and dots in the plot with different colours.我想为图中的线条和点添加不同颜色的图例。 How can I do that?我怎样才能做到这一点? The code I used for plot is as below.我用于绘图的代码如下。 But, I failed to add a desirable legend to that.但是,我没有为此添加一个理想的传说。

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 adds legends automatically if it has groups within the data.如果 ggplot2 在数据中有组,它会自动添加图例。 Your original code provides the minimum amount of information to ggplot(), basically enough for it to work but not enough to create a legend.您的原始代码为 ggplot() 提供了最少量的信息,基本上足以使其工作但不足以创建图例。

Since your data comes from two different objects due to the two different regressions, then it looks like all you need in this case is to add the 'color = "INSERT COLOR NAME"' argument to each geom_point() and each geom_line().由于由于两种不同的回归,您的数据来自两个不同的对象,因此在这种情况下,您似乎只需要向每个 geom_point() 和每个 geom_line() 添加 'color = "INSERT COLOR NAME"' 参数。 Using R's built-in mtcars data set for example, what you have is similar to例如,使用 R 的内置 mtcars 数据集,您所拥有的类似于

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

Graph without Legend无图例图

And what you want can be obtained by using something similar to,你想要的东西可以通过使用类似的东西来获得,

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带图例的图表

Which would seem to translate to这似乎转化为

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

You could also use the size, shape, or alpha arguments inside of aes() to differentiate the different series.您还可以使用 aes() 中的大小、形状或 alpha 参数来区分不同的系列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM