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

b0 <- -90
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 -93.28457
## 2   2 -86.67575
## 3   3 -78.46077
## 4   4 -90.85188
## 5   5 -84.40126
## 6   6 -82.13790
## 7   7 -78.06023
## 8   8 -81.59849
## 9   9 -69.27763
## 10 10 -78.69394
## 11 11 -74.71175
## 12 12 -70.69124
## 13 13 -76.36348
## 14 14 -78.39834
## 15 15 -63.08886
## 16 16 -82.35535
## 17 17 -65.20698
## 18 18 -68.22097
## 19 19 -62.13586
## 20 20 -63.83867
## 21 21 -54.34590
## 22 22 -69.59963
## 23 23 -54.45181
## 24 24 -51.42674
## 25 25 -59.97531
## 26 26 -71.05853
## 27 27 -55.21381
## 28 28 -59.38279
## 29 29 -51.23898
## 30 30 -52.55182
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) -89.1474     2.2356 -39.876  < 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 = rainbow(70), 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