This is my plotly code of Sepal Length vs. Petal Length of the iris dataset, a line of best fit, and a visualization of a 95% confidence interval
# Linear regression model
mod <- lm(Petal.Length ~ Sepal.Length, data = iris)
# x axis
xax <- list(title = "Sepal Length")
# y axis
yax <- list(title = "Petal Length")
# 95% confidence intervals
preds <- predict(mod, newdata = data.frame(Sepal.Length = iris$Sepal.Length), interval = "confidence")
# Plotly plot of scatter, regression model, and confidence interval
plot_ly(iris,
x = ~Sepal.Length,
y = ~Petal.Length,
type = "scatter",
mode = "markers",
name = "data",
height = 450,
width = 700) %>%
add_lines(x = iris$Sepal.Length, fitted(mod),
name = "Overall Fit",
inherit = FALSE) %>%
add_ribbons(x = ~Sepal.Length,
ymin = preds[ , "lwr"],
ymax = preds[ , "upr"],
name = "95% Confidence Interval",
inherit = FALSE,
line = list(color = 'transparent'),
fillcolor = 'rgba(0, 0, 0, 0.15)',
showlegend = TRUE) %>%
layout(xaxis = xax, yaxis = yax) %>%
config(displayModeBar = FALSE) %>%
onRender('
function(el, x) {
setTimeout(function() {
window.dispatchEvent(new Event("resize"));
}, 250);
}
')