title: Add geom_smooth to ggplot facets conditionally based on p-value
body: <p>I'm using ggplot to visualize many linear regressions and facet them by groups. I'd like geom_smooth() to show the trend line as one color if P &lt; 0.05, a different color if P &lt; 0.10, and not show it at all if P ≥ 0.10.</p>
  <p>I managed to do this using a loop to extract P-values from lm() for each regression, then join them with the data used for plotting. Then I add another column of color names to pass to aes(),  determined conditionally from the P-values, and use scale_color_identity() to achieve my goal.</p>
  <p>Here's an example:</p>
  <pre><code>library(tidyverse)
  
  #make mtcars a tibble and cyl a factor, for convenience
  mtcars1 &lt;- as_tibble(mtcars) %&gt;% dplyr::mutate(cyl = as.factor(cyl))
  
  #initialize a list to store p-values from lm() for each level of factor
  p.list &lt;- vector(mode = &quot;list&quot;, length = length(levels(mtcars1$cyl)))
  names(p.list) &lt;- levels(mtcars1$cyl)
  
  #loop to calculate p-values for each level of mtcars$cyl
  for(i in seq_along(levels(mtcars1$cyl))){
    mtcars.sub &lt;- mtcars1 %&gt;% dplyr::filter(cyl == levels(.$cyl)[i])
    
    lm.pval &lt;- mtcars.sub %&gt;% 
      dplyr::distinct(cyl) %&gt;% 
      dplyr::mutate(P = 
                      summary(lm(mpg ~ disp, data = mtcars.sub))$coefficients[2,4] ##extract P-value
      )
    
    p.list[[i]] &lt;- lm.pval
  }
  
  #join p-values to dataset and add column to use with scale_color_identity()
  mtcars.p &lt;- mtcars1 %&gt;% dplyr::left_join(dplyr::bind_rows(p.list, .id = &quot;cyl&quot;), by = &quot;cyl&quot;) %&gt;% 
    dplyr::mutate(p.color = ifelse(P &lt; 0.05, &quot;black&quot;,
                                   ifelse(P &lt; 0.10, &quot;lightblue&quot;, NA)))
  
  #plot
  ggplot(data = mtcars.p, aes(x = disp, y = mpg)) +
    geom_smooth(method = &quot;lm&quot;,
                se = FALSE,
                aes(color = p.color)) +
    geom_point() +
    scale_color_identity(name = NULL,
                         na.translate = FALSE,
                         labels = c(&quot;P &lt; 0.05&quot;, &quot;P &lt; 0.10&quot;),
                         guide = &quot;legend&quot;) +
    facet_wrap(~cyl, scales = &quot;free&quot;)
  </code></pre>
  <p>This seems like too many initial steps for something that should be relatively easy. Are these steps necessary, or is there a more efficient way of doing this? Can ggplot or any other packages out there do this on their own, without having to first extract p-values from lm()?</p>