x <- 1:30
n <- length(x)

b0 <-55
b1 <- 1.2

set.seed(2)
e <- rnorm(n, mean = 0, sd = 5)

y <- b0 + b1 * x + e

ybar <- mean(y)

d <- data.frame(x, y)
d
##     x        y
## 1   1 51.71543
## 2   2 58.32425
## 3   3 66.53923
## 4   4 54.14812
## 5   5 60.59874
## 6   6 62.86210
## 7   7 66.93977
## 8   8 63.40151
## 9   9 75.72237
## 10 10 66.30606
## 11 11 70.28825
## 12 12 74.30876
## 13 13 68.63652
## 14 14 66.60166
## 15 15 81.91114
## 16 16 62.64465
## 17 17 79.79302
## 18 18 76.77903
## 19 19 82.86414
## 20 20 81.16133
## 21 21 90.65410
## 22 22 75.40037
## 23 23 90.54819
## 24 24 93.57326
## 25 25 85.02469
## 26 26 73.94147
## 27 27 89.78619
## 28 28 85.61721
## 29 29 93.76102
## 30 30 92.44818
COL <- c(rgb(255,   0,   0,  255, max = 255),
         rgb(  0,   0, 255,  255, max = 255),
         rgb(  0, 155,   0,  255, max = 255))

matplot(x, y, pch = 1, col = COL[1])
grid()

fit <- lm(y ~ x, data = d)
summary(fit)
## 
## Call:
## lm(formula = y ~ x, data = d)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -13.5989  -2.8452   0.0335   3.6787   9.2076 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  55.8526     2.2356  24.983  < 2e-16 ***
## x             1.2188     0.1259   9.678 1.97e-10 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 5.97 on 28 degrees of freedom
## Multiple R-squared:  0.7699, Adjusted R-squared:  0.7616 
## F-statistic: 93.66 on 1 and 28 DF,  p-value: 1.972e-10
matplot(x, y, pch = 1, col = COL[1], main = '回帰分析')
grid()
matlines(x, fit$fitted, col = COL[2])

library(latex2exp)
legend('topleft', lty = c(NA, 1), pch = c(1, NA), col = COL, 
       legend = c('Data', TeX('$\\hat{y}_i = b_0 + b_1 x_i $')))

library(plotly)
##  要求されたパッケージ ggplot2 をロード中です
## 
##  次のパッケージを付け加えます: 'plotly'
##  以下のオブジェクトは 'package:ggplot2' からマスクされています:
## 
##     last_plot
##  以下のオブジェクトは 'package:latex2exp' からマスクされています:
## 
##     TeX
##  以下のオブジェクトは 'package:stats' からマスクされています:
## 
##     filter
##  以下のオブジェクトは 'package:graphics' からマスクされています:
## 
##     layout

plot_ly() |>
  add_trace(x = x, y = y,          mode = 'markers', name = 'Data') |>
  add_trace(x = x, y = fit$fitted, mode = 'lines',   name = '$\\hat{y}_i = b_0 + b_1 x_i $') |>
  layout(font  = list(size = 11, color = 'blue', family = 'UD Digi Kyokasho NK-R'),
         title = '回帰分析',
         xaxis = list(title = 'x'),
         yaxis = list(title = 'y')) |>
  config(mathjax = 'cdn')
## No trace type specified:
##   Based on info supplied, a 'scatter' trace seems appropriate.
##   Read more about this trace type -> https://plotly.com/r/reference/#scatter
## No trace type specified:
##   Based on info supplied, a 'scatter' trace seems appropriate.
##   Read more about this trace type -> https://plotly.com/r/reference/#scatter