Home > Net >  How to use ggplot2 to plot many regression lines?
How to use ggplot2 to plot many regression lines?

Time:02-28

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?

CodePudding user response:

image

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

CodePudding user response:

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)
  • Related