March 22, 2024

Simple Linear Regression Plotly Plot

data(mtcars)
head(mtcars)
                   mpg cyl disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1
mod <- lm(mpg ~ wt, data = mtcars)


x= mtcars$wt
y = mtcars$mpg

xax <- list(title = "Weight", 
            titlefont = list(family = "Modern Computer Roman"),
            range = c(0, max(x))
            )

yax <- list(title = "Miles per Gallon",
            titlefont = list(family = "Modern Computer Roman"),
            range = c(0, max(y))
            )

linPlot <- plot_ly(x = x, y = y,  type = "scatter", mode = "markers", name = "data",
                   height = 630, width = 630)%>%
  add_lines(x = x, y = fitted(mod), named = "fitted")%>%
  layout(xaxis = xax, yaxis = yax)

config(linPlot, displaylogo = T)
Warning: 'scatter' objects don't have these attributes: 'named'
Valid attributes include:
'cliponaxis', 'connectgaps', 'customdata', 'customdatasrc', 'dx', 'dy', 'error_x', 'error_y', 'fill', 'fillcolor', 'fillpattern', 'groupnorm', 'hoverinfo', 'hoverinfosrc', 'hoverlabel', 'hoveron', 'hovertemplate', 'hovertemplatesrc', 'hovertext', 'hovertextsrc', 'ids', 'idssrc', 'legendgroup', 'legendgrouptitle', 'legendrank', 'line', 'marker', 'meta', 'metasrc', 'mode', 'name', 'opacity', 'orientation', 'selected', 'selectedpoints', 'showlegend', 'stackgaps', 'stackgroup', 'stream', 'text', 'textfont', 'textposition', 'textpositionsrc', 'textsrc', 'texttemplate', 'texttemplatesrc', 'transforms', 'type', 'uid', 'uirevision', 'unselected', 'visible', 'x', 'x0', 'xaxis', 'xcalendar', 'xhoverformat', 'xperiod', 'xperiod0', 'xperiodalignment', 'xsrc', 'y', 'y0', 'yaxis', 'ycalendar', 'yhoverformat', 'yperiod', 'yperiod0', 'yperiodalignment', 'ysrc', 'key', 'set', 'frame', 'transforms', '_isNestedKey', '_isSimpleKey', '_isGraticule', '_bbox'

Simple Linear Regression(ggplot) of the flower dataset

flowers <- read.csv("flower.csv", stringsAsFactors = T, header = T, sep = ",")
data(flowers)
Warning in data(flowers): data set 'flowers' not found
head(flowers)
  treat nitrogen block height weight leafarea shootarea flowers
1   tip   medium     1    7.5   7.62     11.7      31.9       1
2   tip   medium     1   10.7  12.14     14.1      46.0      10
3   tip   medium     1   11.2  12.76      7.1      66.7      10
4   tip   medium     1   10.4   8.78     11.9      20.3       1
5   tip   medium     1   10.4  13.58     14.5      26.9       4
6   tip   medium     1    9.8  10.08     12.2      72.7       9
x =  flowers$weight
y = flowers$height

flowerData <- lm(height ~ weight, data = flowers)
summary(flowerData)
Call:
lm(formula = height ~ weight, data = flowers)

Residuals:
    Min      1Q  Median      3Q     Max 
-7.0010 -2.3129 -0.3104  2.2436  8.7842 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)  4.12030    1.00744   4.090  9.1e-05 ***
weight       0.22372    0.07879   2.839  0.00554 ** 
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 3.063 on 94 degrees of freedom
Multiple R-squared:  0.07899,   Adjusted R-squared:  0.06919 
F-statistic: 8.062 on 1 and 94 DF,  p-value: 0.005541
ggplot(flowers,aes(x = x, y = y)) +
  geom_point(color = "darkgreen") + geom_smooth(method = "lm", color =  "gold") +
  labs(x = "Flower Weight", y = "Flower Height",
       title = "Linear Regression of Flower Weight and Height")
`geom_smooth()` using formula = 'y ~ x'

Simple Linear Regression(ggplot) of the mtcars dataset

data(mtcars)
head(mtcars)
                   mpg cyl disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1
x = mtcars$hp
y = mtcars$qsec

manualCarMod <- lm(y ~ x, data = mtcars)

ggplot(mtcars, aes(x = x, y = y)) +
  geom_point() + geom_smooth(method = "lm") +
  labs(x = "Horse Power", y = " 1/4 Mile Time", 
       title = "Relationship between Horse Power and 1/4 Mile Time")
`geom_smooth()` using formula = 'y ~ x'

Simple Linear Regression General

\(\hat{y} = \beta_0 + \beta_1\cdot \text{x}\)
\(\beta_0 = \text{y-intercept}\)
\(\beta_1 = \text{slope of the line}\)
\(\hat{y} = \text{estimated value of y for some value of x}\)

\(\text{This equation represents the Simple Linear Regression derived from}\) \(\text{the slope-intercept form of the linear equation y = mx + b}\) \(\text{where the slope is based on how steep a line is, change in y over change}\) \(\text{in x. If the slope is positive, the line is moving from bottom left to right}\) \(\text{if the slope is negative, the line is moving from top left to bottom right}\)

\(\text{To calculate slope, we would do}\)
\(\beta_1 = \text{r}\cdot \frac{s_{y}} {s_{x}}\)
\(\text{r} = \text{Pearson's correlation coefficient between x and y}\)
\(s_y = \text{standard deviation of y}\)
\(s_x = \text{standard deviation of x}\)

\(\text{To calculate the y-intercept, we would do: }\)
\(\beta_0 = \bar{y} - \beta_1\cdot \bar{x}\)
\(\bar{y} = \text{mean of y}\)
\(\bar{x} = \text{mean of x}\)
\(\beta_1 = \text{slope}\)

General Residual Equation and Sum of Squared Residuals Equation

\(\text{When making predictions such as the predicted y value or}\)
\(\text{line of best fit, we will generally expect to have some error. These}\)
\(\text{errors in regression prediction are called residuals. Residuals are}\)
\(\text{calculated by finding the difference of an individual's observed y value}\)
\(\text{and thir corresponding predicted y value. Hence, we can expect there to}\)
\(\text{be some error for each indivudal, but we need to construct regression}\)
\(\text{lines that minimizes the squared residuals}\)
\(\text{To calculate residuals, we would do}\)
\(e_{i} = y_{i} - \hat{y_{i}}\)

\(y_{i} = \text{actual value of y for ith observation}\)
\(\hat{y_{i}} = \text{prediced value of y for ith observation}\)

\(\text{To calculate the sum of squared residuals, we would do}\)
\(\text{SSE} = \sum{{(y - \hat{y})}^2}\)

\(\text{The sum of squared residual calculates the accuracy of}\)
\(\text{a simple linear regression model. We calculate this sum}\)
\(\text{by finding the sum of the squared differences between the}\)
\(\text{ovserved values of y and the predict values of y}\)
\(\text{By calculating measure of SSE, we would get a better idea}\)
\(\text{of how well the regression model fits the data. A low SSE}\)
\(\text{means we have a good fitting model, wheras a high SSE}\)
\(\text{indicates we have a poor fitting model}\)

Example Code of Creating Simple Linear Regression Models(ggplot)

\(\text{This sample code is the program I created to create a ggplot of}\)
\(\text{a simple linear regression model of the relationship}\)
\(\text{between flower weight and height}\)

flowers <- read.csv("flower.csv", stringsAsFactors = T, header = T, sep = ",")
#data(flowers)
#head(flowers)

#These are the variables that store the data in columns flower$weight and 
#flower$height, where x contains the data for each flower weight, and y contains
#the data for each flower height. The scaling of the x-axis is based on the
#range from 0 to the max flower weight. 
#The scaling of the y-axis is based on the range from 0 to the max flower height. 
x =  flowers$weight
y = flowers$height

flowerData <- lm(height ~ weight, data = flowers)
summary(flowerData)
Call:
lm(formula = height ~ weight, data = flowers)

Residuals:
    Min      1Q  Median      3Q     Max 
-7.0010 -2.3129 -0.3104  2.2436  8.7842 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)  4.12030    1.00744   4.090  9.1e-05 ***
weight       0.22372    0.07879   2.839  0.00554 ** 
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 3.063 on 94 degrees of freedom
Multiple R-squared:  0.07899,   Adjusted R-squared:  0.06919 
F-statistic: 8.062 on 1 and 94 DF,  p-value: 0.005541
#Creates the ggplot
# ggplot(flowers,aes(x = x, y = y)) +
#   geom_point(color = "darkgreen") + geom_smooth(method = "lm", color =  "gold") +
#   labs(x = "Flower Weight", y = "Flower Height",
#        title = "Linear Regression of Flower Weight and Height")

Example Code of creating Simple Linear Regression Model(plot_ly)

\(\text{This sample code is the program I created to create a plotly plot of}\)
\(\text{a simple linear regression model of the relationship}\)
\(\text{between car weight and miles per gallon}\)

data(mtcars)
head(mtcars)
                   mpg cyl disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1
mod <- lm(mpg ~ wt, data = mtcars)


#These are the variables that store the data in columns mtcars$weight and 
#flower$mpg, where x contains the data for the weights of each car, and 
#y contains the data for the miles per gallon rates of each cat
x= mtcars$wt
y = mtcars$mpg

#This section of code consists of the title and ranges of the scales
#for the x-axis and y-axis of the simple linear regression model
xax <- list(title = "Weight", 
            titlefont = list(family = "Modern Computer Roman"),
            range = c(0, max(x))
            )

yax <- list(title = "Miles per Gallon",
            titlefont = list(family = "Modern Computer Roman"),
            range = c(0, max(y))
            )


#This portion of the code creates the plotly plot

# linPlot <- plot_ly(x = x, y = y,  type = "scatter", mode = "markers", name = "data",
#                    height = 630, width = 630)%>%
#   add_lines(x = x, y = fitted(mod), named = "fitted")%>%
#   layout(xaxis = xax, yaxis = yax)
# 
# config(linPlot, displaylogo = T)