How to add a trendline to a two variables, two y-axes plot in r? -
i have dataset
structure(list(year = 1988:2012, = 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))
and created plot twoord.plot
function:
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")
how should tell second trendline (the red one) belongs righ hand y-axis? possible in r?
i guess r knows 1 scale x , 1 y. if have function twoord.plot
can see adds right hand plot scaling-offest operation :
points(rx, ry * ymult + yoff, col = rcol, pch = rpch, type = type[2], ...)
my guess have same add lines. selecting lines function, should (ly = example$b
, ry = 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")
Comments
Post a Comment