title: How to visualize GAM results with contour & tile plot (using ggplot2)
body: <p>I would like to make a contour plot with <code>ggplot2</code> by using <code>gam</code> results. Below is a detailed explanation of what I want:</p>
  <pre><code>#packages
  library(mgcv)
  library(ggplot2)
  library(tidyr)  
  #prepare data
  df &lt;- data.frame(x = iris$Sepal.Width,
                   y = iris$Sepal.Length,
                   z = iris$Petal.Length)
  #fit gam
  gam_fit  &lt;- gam(z ~
                    s(x) +
                    s(y),
                  data=df,na.action = &quot;na.fail&quot;)
  </code></pre>
  <p>To predict z values based on the <code>gam_fit</code>, I found a way from <a href="https://drmowinckels.io/blog/2019-11-16-plotting-gamm-interactions-with-ggplot2/" rel="nofollow noreferrer">https://drmowinckels.io/blog/2019-11-16-plotting-gamm-interactions-with-ggplot2/</a></p>
  <pre><code>#predict z values
  df_pred &lt;- expand_grid(
    x = seq(from=min(df$x), 
                to=max(df$x), 
                length.out = 100),
    y = seq(from=min(df$y), 
                to=max(df$y), 
                length.out = 100)
  )
  df_pred &lt;- predict(gam_fit, newdata = df_pred, 
                        se.fit = TRUE) %&gt;%  
      as_tibble() %&gt;% 
      cbind(df_pred)
  gg &lt;- ggplot() +
    geom_tile(data=df_pred, aes(x=x, y=y, fill = fit)) +
    geom_point(data=df,aes(x=x, y=y))+
    scale_fill_distiller(palette = &quot;YlGnBu&quot;)+
    geom_contour(data=df_pred, aes(x=x, y=y, z = fit), colour = &quot;white&quot;)
  print(gg)
  </code></pre>
  <p>This give me a below plot
  <a href="https://i.stack.imgur.com/PgBSi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PgBSi.png" alt="enter image description here" /></a></p>
  <p>My goal is removing tile and contour at where there are no measured x-y points. For example, there is no measured points around the top-right &amp; top-left corners of the plot.</p>
  <p>I wonder if <code>mgcViz</code> can achieve this, but it requires including x &amp; y as an interaction term as below (also I am not sure how to add measured points on the below figure):</p>
  <pre><code>library(mgcViz)
  gamm_fit2  &lt;- gam(z ~
                     s(x,y),
                  data=df,na.action = &quot;na.fail&quot;) #,REML=TRUE
  b &lt;- getViz(gamm_fit2)
  plot(sm(b, 1))
  </code></pre>
  <p><a href="https://i.stack.imgur.com/BF7nS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BF7nS.png" alt="enter image description here" /></a></p>
  <p>I think <code>df_pred</code> may not the best format to achieve my goal, but I am not sure how to do this. I would be grateful if you give me any solution with <code>ggplot2</code>.</p>