我创建了一个双y轴图,使用plotrix
包显示两组点,下一步是分别为两组点添加回归线。但我不知道如何处理这种情况。有什么建议?先感谢您!
用于创建双y轴图的示例代码:
library(plotrix)
xval1 <- seq.Date(as.Date("2017-01-02"),
as.Date("2017-01-10"), by="day")
xval2 <- seq.Date(as.Date("2017-01-01"),
as.Date("2017-01-15"), by="day")
going_up <- seq(3,7,by=0.5)+rnorm(9)
going_down <- rev(60:74)+rnorm(15)
twoord.plot(2:10, going_up,1:15, going_down, xlab="Sequence", type = 'p',
ylab = "Ascending values",rylab="Descending values",lcol=4)
由于twoord.plot
的帮助建议对地块的任何进一步添加将相对于左边纵坐标绘制,这是一个机器人技巧。
请注意,可以使用点或线将更多值添加到绘图中,但请记住,这些值将相对于左侧纵坐标绘制。
但我认为可以通过一些缩放来完成。首先,我们将您的数据转换为数据框,以便我们可以拟合回归:
df1 <- data.frame(y = going_up, x = 2:10)
res1 <- lm(y ~ x, df1) #fit
pred1 <- predict(res1, df1) #generate point for plotting
而对于第二个:
df2 <- data.frame(y = going_down, x = 1:15)
res2 <- lm(y ~ x, df2)
pred2 <- predict(res2, df2)
现在因为pred2与pred1完全不同,我们需要将它缩放到pred1的范围,rescale
可以使用scales
。我填充定义两个缩放范围:
pred2 <- scales::rescale(pred2, to = c(2, 8), from = c(58, 76))
我将在rylim
中使用这些范围作为参数lylim
和twoord.plot
:
twoord.plot(2:10, going_up, 1:15, going_down, xlab = "Sequence", type = 'p',
ylab = "Ascending values", rylab = "Descending values", lcol = 4, rylim = c(58, 76), lylim = c(2, 8))
lines(2:10, pred1, col = "blue")
lines(1:15, pred2, col = "red")
检查它是否与我们仅绘制pred2时相似:
pred2 <- predict(res2, df2)
plot(1:15, going_down)
lines(1:15, pred2)