geom_abline

时间:2022-07-22
本文章向大家介绍geom_abline,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Lines: horizontal, vertical, and specified by slope and intercept.

Usage

geom_abline(mapping = NULL, data = NULL, ..., slope, intercept, na.rm = FALSE, show.legend = NA)

geom_hline(mapping = NULL, data = NULL, ..., yintercept, na.rm = FALSE, show.legend = NA)

geom_vline(mapping = NULL, data = NULL, ..., xintercept, na.rm = FALSE, show.legend = NA)

p <- ggplot(mtcars, aes(wt, mpg)) + geom_point()# Fixed values p + geom_vline(xintercept = 5)

p + geom_vline(xintercept = 1:5)

p + geom_hline(yintercept = 20)

p + geom_abline() # Can't see it - outside the range of the data

p + geom_abline(intercept = 20)

# Calculate slope and intercept of line of best fit
coef(lm(mpg ~ wt, data = mtcars))(Intercept)          wt
 37.285126   -5.344472p + geom_abline(intercept = 37, slope = -5)

# But this is easier to do with geom_smooth: p + geom_smooth(method = "lm", se = FALSE)

# To show different lines in different facets, use aesthetics p <- ggplot(mtcars, aes(mpg, wt)) + geom_point() + facet_wrap(~ cyl)

# You can also control other aesthetics ggplot(mtcars, aes(mpg, wt, colour = wt)) + geom_point() + geom_hline(aes(yintercept = wt, colour = wt), mean_wt) + facet_wrap(~ cyl)mean_wt <- data.frame(cyl = c(4, 6, 8), wt = c(2.28, 3.11, 4.00)) p + geom_hline(aes(yintercept = wt), mean_wt)