nicholas
nicholas

Reputation: 983

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)

enter image description here

How can I do the same thing using ggplot2?

Upvotes: 1

Views: 154

Answers (2)

stomper
stomper

Reputation: 1387

image

priors %>%
    ggplot() +
    geom_abline(aes(intercept =  a, slope = bN)) +
    xlim(-2,2) +
    ylim(-2,2) +
    theme_classic()

Upvotes: 4

Ben Bolker
Ben Bolker

Reputation: 226057

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)

Upvotes: 1

Related Questions