2023-02-10

Plotly Linear Regression with iris Dataset

GGPlot iris

## `geom_smooth()` using formula = 'y ~ x'

GGPlot mtcars

## `geom_smooth()` using formula = 'y ~ x'

Simple Linear Regression Formula

\(y = \beta_0 + \beta_1\cdot x + \varepsilon\), where \(\varepsilon \sim \mathcal{N}(\mu=0; \,\,\sigma^2)\)

Mean Squared Error for Linear Regression

\(\displaystyle MSE = {SSE \over n-2} = {1\over n-2} \sum_{i=1}^n (y_i - \hat{y}_i)^2\)

R Code for Plotly Regression

y = iris$Petal.Length; x = iris$Sepal.Length
mod = lm(y~x)

xax <- list(title = "Sepal Length")
yax <- list(title = "Petal Length")

fig <- plot_ly(x = iris$Sepal.Length, y = iris$Petal.Length,
        type = "scatter",
        mode = "markers",
        name = "SL vs. PL") %>%
        add_lines(x = x, y = fitted(mod), name = "Lin Reg") %>%
        layout(xaxis = xax, yaxis = yax)
config(fig, displaylogo=FALSE) 

R Code for GGPlot Regression

g <- ggplot(iris, aes(x = Sepal.Length,y = Petal.Length)) + geom_point()
g + geom_smooth(formula = y ~ x, method = "lm")