| Top Page | プログラミング | R 自動化 目次 | 6章へ |

d <- read.table('len_width.txt', header = TRUE) 
d.sp1 <- d[d$sp == 'Sp1',]
d.sp2 <- d[d$sp == 'Sp2',]

# type = 'n' で,プロットはせず軸やラベルだけ描く.
plot(d$len, d$width, type = 'n', xlab = "Length", ylab = "Width",
main = "Model fitting using glm")

# それぞれの種の点をプロット.色は番号で指定.cex で大きめの点に.
points(d.sp1$len, d.sp1$width, col = 1, cex = 1.5)
points(d.sp2$len, d.sp2$width, col = 2, cex = 1.5)

# Sp2 へのモデルあてはめ
lf1 <- glm(d.sp1$width ~ 1 + d.sp1$len)     #  モデルのあてはめ結果を lf にしまう.
cf1 <- lf1$coefficients              # あてはめたモデルの係数を変数 cf にしまう.
curve(cf1[1] + cf1[2] * x, from = min(d$len), to = max(d$len), add = TRUE, col = 1)

# Sp2 へのモデルあてはめ
lf2 <- glm(d.sp2$width ~ 1 + d.sp2$len)     #  モデルのあてはめ結果を lf にしまう.
cf2 <- lf2$coefficients              # あてはめたモデルの係数を変数 cf にしまう.
curve(cf2[1] + cf2[2] * x, from = min(d$len), to = max(d$len), add = TRUE, col = 2)

par('usr') -> usr                      #  現在の座標系を取得
x <- usr[1] + (usr[2] - usr[1]) * 0.3 

y <- (usr[4] - usr[3]) * 0.9 + usr[3]  #  y軸の,下から 90% のところ.
eq <- sprintf('y = %.3f * x + %.3f', cf1[2], cf1[1])
text(x, y, eq, col = 1)

y <- (usr[4] - usr[3]) * 0.8 + usr[3]  #  y軸の,下から 80% のところ.
eq <- sprintf('y = %.3f * x + %.3f', cf2[2], cf2[1])
text(x, y, eq, col = 2)

| Top Page | プログラミング | R 自動化 目次 | 6章へ |