# Plot the confidence interval for a model fit

**URL:** <https://discourse.julialang.org/t/plot-the-confidence-interval-for-a-model-fit/37767>\
**Category:** Statistics\
**Tags:** plotting, fit, glm\
**Created:** [April 17, 2020, 3:52pm UTC](https://discourse.julialang.org/t/plot-the-confidence-interval-for-a-model-fit/37767 "2020-04-17T15:52:05Z")\
**Posts on this page:** 1\
**Showing post:** 4

<div class="post-metadata">

**Author:** ![nilshg](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/nilshg/32/2283_2.png) [@nilshg](https://discourse.julialang.org/u/nilshg)\
**Post date:** [April 17, 2020, 9:06pm UTC](https://discourse.julialang.org/t/plot-the-confidence-interval-for-a-model-fit/37767/4 "2020-04-17T21:06:43Z")

</div>

EDIT: I accidentally led this thread down a rabbit hole by plotting a _prediction_ interval rather than a _confidence_ interval below, and also bungling the use of `ribbon`. Long story short the ggplot2 plot shown below can also be obtained in Plots.jl/GLM.jl if one calls `predict(model, pred, interval = :confidence, level = 0.95)`.

@BLI has the right plot command, let me add the GLM command you are probably after:

```julia

using DataFrames, GLM, Plots
data = DataFrame(x = rand(100));
data.y = 1 .+ 2*data.x .+ 0.1*rand(100);

model = lm(@formula(y ~ x), data)
pred = DataFrame(x = 0:0.01:1);
pr = predict(model, pred, interval = :prediction, level = 0.95)

plot(xlabel="x", ylabel="y", legend=:bottomright)
plot!(data.x, data.y, label="data", seriestype=:scatter)
plot!(pred.x, pr.prediction, label="model", linewidth=3, 
        ribbon = (pr.prediction .- pr.lower, pr.upper .- pr.prediction))

```

 ![image](https://global.discourse-cdn.com/julialang/original/3X/c/c/ccd5e3396801b969a79277239b618fc7685b7371.png)

The relevant docstring is:

```julia
?help> predict

  predict(mm::LinearModel, newx::AbstractMatrix;
          interval::Union{Symbol,Nothing} = nothing, level::Real = 0.95)

  If interval is nothing (the default), return a vector with the predicted values for model mm and new data newx. Otherwise, return a 3-column matrix with the prediction and the lower and upper confidence bounds for a given level (0.95 equates alpha = 0.05).
  Valid values of interval are :confidence delimiting the uncertainty of the predicted relationship, and :prediction delimiting estimated bounds for new data points.

```

---

_[View the full topic](https://discourse.julialang.org/t/plot-the-confidence-interval-for-a-model-fit/37767)._
