如何将趋势线添加到两个变量中,两个y轴绘制在r?

时间:2015-04-29 10:17:50

标签: r

我有这个数据集

structure(list(Year = 1988:2012, A = c(1415.6, 1345.3, 1321.7, 
1234.5, 1567.8, 1476.6, 1610.1, 1422.6, 1209.1, 1249.3, 1377.5, 
1525.7, 1683.7, 1500.1, 1565.3, 1737.4, 1321, 1477.8, 1642, 1608.1, 
1427.8, 1608.2, 1404.4, 1688.3, 1795.4), B = c(76, 359, 299, 
215, 177, 3112, 12047, 26307, 27173, 6514, 4190, 1776, 1708, 
1335, 1012, 8170, 4306, 3716, 23531.986, 34803.012, 22758.7645, 
29140.16304, 36369.3619, 56975.62256, 33516.95628)), .Names = c("Year", 
"A", "B"), class = "data.frame", row.names = c(NA, -25L))

我用twoord.plot函数创建了这个图:

install.packages("plotrix")
library(plotrix)

twoord.plot(Example$Year, Example$B, Example$Year, Example$A, xlim = range(1988:2012))
abline(lm(B ~ Year, data = Example), col="black")
abline(lm(A ~ Year, data = Example), col="red")

enter image description here

我应该如何判断它属于右手y轴的第二条趋势线(红线)?可以在r中做到吗?

1 个答案:

答案 0 :(得分:2)

我猜R只知道x的一个比例,y知道一个比例。如果您查看函数twoord.plot,您可以看到它添加右手图以及缩放操作:

points(rx, ry * ymult + yoff, col = rcol, pch = rpch, 
    type = type[2], ...)

我的猜测是你必须做同样的事情来增加额外的线条。只需在函数中选择一些行,它应该是(ly = Example$Bry = Example$A):

lylim <- range(ly, na.rm = TRUE)
rylim <- range(ry, na.rm = TRUE)
ymult <- diff(lylim)/diff(rylim)
yoff <- lylim[1] - rylim[1] * ymult
coef = lm(A ~ Year, data = Example)$coefficients
abline(a = coef[1]*ymult + yoff, b = coef[2]*ymult, col="red")