简体   繁体   中英

How to limit the length of abline in ggplot2 using slope and intercept?

How I can limit the length of abline to only between year 1985 to 1990 using the slope and intercept. I know geom_segment but it does not take slope and intercept. Here is my data and script

> dput(df)
structure(list(year = c(1979, 1980, 1981, 1982, 1983, 1984, 1985, 
1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 
1997, 1998), value = c(7.33, 10.32, 11.65, 6.19, 8.3, 9.24, 8.13, 
9.94, 10.85, 11.37, 7.17, 9.18, 11.24, 11.38, 8.32, 9.29, 7.48, 
8.63, 10.17, 8.94)), .Names = c("year", "value"), row.names = c(NA, 
-20L), class = c("tbl_df", "tbl", "data.frame"))

Script

plt <- ggplot(df, aes(year, value)) +
    geom_line() +
    geom_abline(aes(slope = 0.00225, intercept = 4.85100), colour = "red", lty = "dashed")

plt

Just use geom_segment . It's trivial to calculate the y endpoints given the x endpoints and the slope and intercept.

xs = c(1985, 1990)
beta = c(4.851, .00225)
ys = cbind(1, xs) %*% beta

... +
geom_segment(aes(x = xs[1], xend = xs[2], y = ys[1], yend = ys[2]),
    colour = "red",lty = "dashed")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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