2024-03-08

Sample Usecase

Today we will cover how we can take a simple data set and create a predictive model for a property based solely on the square footage.

General Overview

  1. Import the Data Set
  2. Plot it as a scatter plot
  3. Insert a Line of Best Fit (LoBF)
  4. Add additional labels
  5. [Optional] Upgrade to plotly for more interaction

Importing and Plotting

Adding a Line of Best Fit (LoBF)

  1. Lets add a LoBF!

Underlying Theory

We are iteratively fitting a linear equation to the scattered data. This allows us to model the previously disconnected data with a mathematical equation \[ y = mx + c \]

where:

  • \(y\) is the dependent variable,
  • \(x\) is the independent variable,
  • \(m\) is the slope of the line, and
  • \(c\) is the y-intercept.

Using it to predict a value

Begin by taking the LoBF calculated in the previous slide. \[ y = 462x + 2387308.5 \] we can then insert a hypothetical square footage. Let’s choose 14,000.

\[ y = 462(14000) + 2387308.5 \] \[ y = 8,855,308.50 \]

Recreating the original visualization with Plotly

We can take the visualization one step further using plotly.

library(plotly)

## Create the Scatter Plot
plot <- plot_ly(housing, x = ~area, y = ~price, 
                type = 'scatter', mode = 'markers')

## Add the LoBF
plot <- add_lines(plot, x = ~area, 
                  y = ~fitted(lm(price ~ area, housing)), 
                  name = "Predictive Model")

## Create additional customization/labels
plot <- layout(plot, title = "Square Footage vs. Price",
               xaxis = list(title = "Square Footage"),
               yaxis = list(title = "Price in $"))

plot

Recreated Visualization