'How to use ggplot2 to plot many regression lines?
I am trying plot 50 simulated regression lines. I can do the plot in base R, but I'm struggling to do it with ggplot2
Simulated data:
library(tidyverse)
set.seed(5)
priors <- tibble(a = rnorm(n = 50, mean = 0, sd = 1),
bN = rnorm(n = 50, mean = 0, sd = 1))
Desired output using base R:
plot( NULL , xlim=c(-2,2) , ylim=c(-2,2) )
for(i in 1:50) curve(priors$a[i] + priors$bN[i]*x,
from = -2, to = 2, add = TRUE)
How can I do the same thing using ggplot2?
Solution 1:[1]
geom_abline() adds a line with specified intercept and slope.
gg0 <- ggplot() + scale_x_continuous(limits=c(-2,2)) +
scale_y_continuous(limits=c(-2,2))
gg <- gg0
for (i in 1:50) {
gg <- gg + geom_abline(intercept=priors$a[i],slope = priors$bN[i])
}
print(gg)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ben Bolker |

