#author("2019-02-26T06:43:59+00:00","","")
[[R言語入門]] >
* R言語でグラフ描画 [#t7fcddf2]
#mynavi(R言語入門);
#setlinebreak(on);

* 目次 [#c5597d22]
#html(<div style="padding-left: 10px;">)
#contents
-- 関連
--- [[R言語入門]]
- 関連
-- [[R言語入門]]
-- [[Rでテキストマイニング]]
-- [[機械学習の為の数学の基礎]]
#html(</div>)

#TODO
* グラフ描画の基本 [#yced50a2]
#html(<div style="padding-left: 10px;">)

** png画像として出力する [#kf3e78dc]
グラフ描画は基本的に以下の手順で行う。

+ 描画デバイスを開く
+ グラフデータをプロットする
+ グラフの装飾(追加情報の描画)
+ 描画デバイスを閉じる

 ※ R Studio の場合は描画デバイスのオープン、クローズは無くてもOK。(プロット領域に表示される)

折れ線グラフの描画例)
#myterm2(){{
x <- c(1, 2, 3, 4, 5)
y <- c(2, 3, 4, 8, 10)
dev.new()                                  # 1. 描画デバイスを開く
plot(x, y)                                   # 2. データのプロット
lines(x, y)                                  # 3. 線の追加 ※ plot(x, y, type="b") 等で一発で書く事も可能
dev.off()                                    # 4. 描画デバイスを閉じる
}}
#html(</div>)

* plot 関数の使用方法 [#naf31e6f]
#html(<div style="padding-left: 10px;">)

グラフ描画で最もよく使用する plot について記載する。

形式)
| plot(x, y, ...) |

引数)
| 引数 | 説明 |h
| x | X軸のデータ |
| y | Y軸のデータ |
| type | "p": 点を描画 |
|~| "l": 線のみを描画 |
|~| "b": 点と線の両方を描画 |
|~| "c": 線のみを描画( 点の部分は空白になる ) |
|~| "o": 点と線の両方を描画( "l" との違いは点の描画域の余白がない事 ) |
|~| "h": 垂直線の描画(ヒストグラム?) |
|~| "s": 階段グラフの描画 |
|~| "S" s の反転グラフ |
|~| "n": データの描画はしない(プロット領域の初期化のみ行う) |
| main | タイトル(描画領域の上部に表示される) |
| sub | サブタイトル(描画領域の下部に表示される) |
| xlab | X軸のタイトル |
| ylab | Y軸のタイトル |
| asp | x/y のアスペクト比。&br;※ plot.windowで使用されるパラメータ |
| xlim | X軸の描画範囲&br;※ plot.windowで使用されるパラメータ |
| ylim | Y軸の描画範囲&br;※ plot.windowで使用されるパラメータ |
| log | 対数スケールする軸を指定する ※ "x"or "y" or "xy" |
| ann | タイトル、X軸 及び  Y軸のラベルを表示するかどうか。(T or F)|
| axes | X軸、Y軸を表示するかどうか。( T or F )&br;※ Fにした場合は枠自体が表示されない。 |
| xaxt&br;yaxt | X軸、Y軸メモリを表示するかどうか。( 表示しない場合は "n" を指定 ) |
| frame.plot | 枠を表示するかどうか ( T or F ) |
| panel.first | プロット軸が設定された後、プロットが行われる前に評価される式。|
| panel.last | プロットが行われた後、Axes、title、boxが追加される前に評価される式。 |
// cex	 点のサイズ、指定しない場合は1
// cex
// A numerical value giving the amount by which plotting text and symbols should be magnified relative to the default. This starts as 1 when a device is opened, and is reset when the layout is changed, e.g. by setting mfrow.
// Note that some graphics functions such as plot.default have an argument of this name which multiplies this graphical parameter, and some functions such as points and text accept a vector of values which are recycled.
// cex.axis
// The magnification to be used for axis annotation relative to the current setting of cex.
// cex.lab
// The magnification to be used for x and y labels relative to the current setting of cex.
// cex.main
// The magnification to be used for main titles relative to the current setting of cex.
// cex.sub
// The magnification to be used for sub-titles relative to the current setting of cex.

例えば、以下のように type="l" を指定すれば線だけを描画できる。
#myterm2(){{
x <- c(1, 2, 3, 4, 5)
y <- c(2, 3, 4, 8, 10)
#dev.new()                                                        # 描画デバイスを開く
png("plot1.png", width=480, height=480)      # pngファイルを描画デバイスとして開く
plot(x, y)                                   # グラフを描く
#points(approx(x, y))               # 線形補間
lines(x, y)                                  # 折れ線グラフ
dev.off()                                    # 描画デバイスを閉じる
dev.new()
plot(x, y, type="l")   # 線だけを描画
dev.off()
}}

#html(</div>)

* グラフの描画/装飾方法 [#m5fdeef0]
#html(<div style="padding-left: 10px;">)

plot 後にも追加の点や線、文字列などを描画する事ができる。

** 点の描画 [#b83a4b3c]
#html(<div style="padding-left: 10px;">)
#myterm2(){{
x <- 1:10
y <- rnorm(10, seq(1, 10, by = 1), 1)
plot(x, y, type="l")    # 線のみ描画
points(x, y)                # 点を描画
}}
#html(</div>)

** 線の描画 [#bef6ffa1]
#html(<div style="padding-left: 10px;">)
#myterm2(){{
x <- 1:10
y <- rnorm(10, seq(1, 10, by = 1), 1)
plot(x, y, type="p")               # 点のみ描画
lines(x, y)                              # 線を描画
abline(lm(y~x), col="red")    # 回帰直線を赤で描画
}}
#html(</div>)

** タイトルの描画 [#s7a9b8b0]
#html(<div style="padding-left: 10px;">)
#myterm2(){{
x <- 1:10; y <- 1:10; 
plot(x, y, type="b")
title(main="main title", sub = "sub title")      # タイトル/サブタイトルを描画
}}
#html(</div>)

** 文字の描画 [#s2165d86]
#html(<div style="padding-left: 10px;">)
グラフの任意の位置に文字を描画する場合は text を使用する。

形式)
| text(x, y = NULL, labels = seq_along(x$x), adj = NULL, pos = NULL, offset = 0.5, vfont = NULL, cex = 1, col = NULL, font = NULL, ...) |

例)
#myterm2(){{
x <- 1:10; y <- 1:10; 
plot(x, y, type="b")
text(10, 1, "Test!")   # x=10, y=1 の位置に文字を描画
}}
#html(</div>)

#html(<div style="padding-left: 10px;">)
グラフの余白部分に文字を描画する場合は mtext を使用する。

形式)
| mtext(text, side = 3, line = 0, outer = FALSE, at = NA, adj = NA, padj = NA, cex = NA, col = NA, font = NA, ...) |

例)
#myterm2(){{
x <- 1:10; y <- 1:10; 
plot(x, y, type="b")
mtext("Bottom!", side=1)    # 下に描画
mtext("Left!", side=2)         # 左に描画
mtext("Top!", side=3)         # 上に描画
mtext("Right!", side=4)      # 右に描画
}}

#html(</div>)

** 枠、座標軸の描画 [#c46723f5]
#html(<div style="padding-left: 10px;">)

枠は box で、座標軸は axis で描画する。

形式)
| box(which = "plot", lty = "solid", ...) |

形式)
| axis(side, at = NULL, labels = TRUE, tick = TRUE, line = NA, &br;&nbsp;&nbsp;     pos = NA, outer = FALSE, font = NA, lty = "solid", &br;&nbsp;&nbsp;     lwd = 1, lwd.ticks = lwd, col = NULL, col.ticks = NULL, &br;&nbsp;&nbsp;     hadj = NA, padj = NA, ...) |

例)
#myterm2(){{
x <- 1:10
y <- 1:10
plot(x, y, axes=F)  # 枠 及び 軸なしでプロット
axis(side=1)          # X軸を描く
axis(side=2)          # Y軸を描く
box()                      # 枠を描く
}}
#html(</div>)

** 凡例の描画 [#ofa4b9d3]
#html(<div style="padding-left: 10px;">)

legend で判例を描画する事ができる。

形式)
| legend(x, y = NULL, legend, fill = NULL, col = par("col"),&br;&nbsp;&nbsp;       border = "black", lty, lwd, pch,&br;&nbsp;&nbsp;       angle = 45, density = NULL, bty = "o", bg = par("bg"),&br;&nbsp;&nbsp;       box.lwd = par("lwd"), box.lty = par("lty"), box.col = par("fg"),&br;&nbsp;&nbsp;       pt.bg = NA, cex = 1, pt.cex = cex, pt.lwd = lwd,&br;&nbsp;&nbsp;       xjust = 0, yjust = 1, x.intersp = 1, y.intersp = 1,&br;&nbsp;&nbsp;       adj = c(0, 0.5), text.width = NULL, text.col = par("col"),&br;&nbsp;&nbsp;       text.font = NULL, merge = do.lines && has.pch, trace = FALSE,&br;&nbsp;&nbsp;       plot = TRUE, ncol = 1, horiz = FALSE, title = NULL,&br;&nbsp;&nbsp;       inset = 0, xpd, title.col = text.col, title.adj = 0.5,&br;&nbsp;&nbsp;       seg.len = 2) |

例)
#myterm2(){{
x <- 1:10
y1 <- rnorm(10, seq(1, 10, by = 1), 1)
y2 <- rnorm(10, seq(1, 10, by = 1), 1)
y3 <- rnorm(10, seq(1, 10, by = 1), 1)
plot(x, y1, type="l", col="black")
lines(x, y2, col="red")
lines(x, y3, col="green")
legend(x=8, y=4, paste("test",c(1:3), sep=""), col=c("black","red","green"), lwd=1, merge=F, bg="lightgray")
}}
#html(</div>)

** グリッドの描画 [#h41a04f0]
#html(<div style="padding-left: 10px;">)

grid でグラフにグリッド線を描画する事ができる。

形式)
| grid(nx = NULL, ny = nx, col = "lightgray", lty = "dotted",&br;&nbsp;&nbsp;     lwd = par("lwd"), equilogs = TRUE) |

例)
#myterm2(){{
x < 1:10
y < rnorm(10, seq(1, 10, by = 1), 1)
plot(x, y, type="o")
grid(10, 10)                  # グリッドを描画
}}
#html(</div>)

** 四角形の描画 [#w6ae4624]
#html(<div style="padding-left: 10px;">)

四角形を描画するには rect を使用する。

形式)
| rect(xleft, ybottom, xright, ytop, density = NULL, angle = 45,&br;&nbsp;&nbsp;     col = NA, border = NULL, lty = par("lty"), lwd = par("lwd"),&br;&nbsp;&nbsp;     ...) |

例)
#myterm2(){{
plot(1:10, 1:10)
rect(8, 2, 10, 1, col="red")
}}
#html(</div>)

** 多角形の描画 [#a327a6c7]
#html(<div style="padding-left: 10px;">)
#myterm2(){{
plot(1:10, 1:10, type="n", xlab="", ylab="")
polygon(c(4,6,8), c(4,8,4), col="red")    # 三角形を書いてみる
}}
#html(</div>)

** 矢印の描画 [#g2f738a1]
#html(<div style="padding-left: 10px;">)

arrows で矢印が描画できる。

形式)
| arrows(x0, y0, x1 = x0, y1 = y0, length = 0.25, angle = 30,&br;&nbsp;&nbsp;       code = 2, col = par("fg"), lty = par("lty"),&br;&nbsp;&nbsp;       lwd = par("lwd"), ...) |

例)
#myterm2(){{
plot(1:10, 1:10, type="n", xlab="", ylab="")
arrows(2,2,8,8, code=2, angle=30, length=0.1, lwd=2)
}}

#html(</div>)

#html(</div>)

* グラフ描画用のパラメータ設定 [#d380de9b]
#html(<div style="padding-left: 10px;">)

グラフ描画用の各種パラメータは plot 時のパラメータ以外に par でも設定する事ができる。
以下に例を記載する。

** 例) 日本語フォントを設定する [#q5602f85]
#html(<div style="padding-left: 10px;">)
#myterm2(){{
x <- c(1, 2, 3, 4, 5)
y <- c(2, 3, 4, 8, 10)
plot(x, y)
par(family = "Meiryo")                                 # 日本語フォントを設定
title(main="テストタイトル", sub = "サブタイトル")      # タイトル/サブタイトルを描画
}}
#html(</div>)

** 例) 線を太くする [#t3bac0bc]
#html(<div style="padding-left: 10px;">)
#myterm2(){{
x <- c(1, 2, 3, 4, 5)
y <- c(2, 3, 4, 8, 10)
plot(x, y)
par(lwd=3)
lines(x, y)
}}
#html(</div>)

引数なしで par() すると、現在の設定が取得できる。
#myterm2(){{
> par()
$xlog
[1] FALSE

$ylog
[1] FALSE

$adj
[1] 0.5

$ann
[1] TRUE
.
.
.
}}

#html(</div>)

* グラフの描画例 [#m411ecaa]
#html(<div style="padding-left: 10px;">)

** 点グラフ(線形補間) [#o60d4644]
#html(<div style="padding-left: 10px;">)
#myterm2(){{
x <- c(1, 2, 3, 4, 5)
y <- c(2, 3, 4, 8, 10)
dev.new()
plot(x, y)
points(approx(x, y))               # 線形補間
dev.off()
}}
#html(</div>)

** 折れ線グラフ [#t92bf867]
#html(<div style="padding-left: 10px;">)
#myterm2(){{
x <- c(1, 2, 3, 4, 5)
y <- c(2, 3, 4, 8, 10)
dev.new()
plot(x, y)
lines(x, y)                        # 線グラフ描画
dev.off()
}}
#html(</div>)

** 線形回帰(回帰直線) [#fe092193]
#html(<div style="padding-left: 10px;">)
#myterm2(){{
x <- c(1, 2, 3, 4, 5)
y <- c(2, 3, 4, 8, 10)
dev.new()
plot(x, y)
result <- lm(y~x)            # 線型モデルによる回帰分析を行い回帰式を得る
fitted_y = fitted(result)   # 回帰式により予測値を求める
lines(x, fitted_y)              # 線グラフの描画
# abline(result)               # abline でも同じく回帰直線が描ける(直線回帰の結果を引数に指定する)
dev.off()
}}

#html(</div>)

** ヒストグラム [#u270f118]
#html(<div style="padding-left: 10px;">)
例) 身長のランダムデータを作成し、ヒストグラム化する。
#myterm2(){{
> x = rnorm(100, mean = 170, sd = 10)
> hist(x)
}}
#html(</div>)

** ロジスティック回帰 [#o658737b]
#html(<div style="padding-left: 10px;">)
#TODO
#html(</div>)

// *** 分散分析
// #html(<div style="padding-left: 10px;">)
// #TODO
// #html(</div>)

** XXXXXXXXXX [#u305d565]
#html(<div style="padding-left: 10px;">)
#TODO
#html(</div>)

#html(</div>)

* ファイルへの出力 [#f10227f7]
#html(<div style="padding-left: 10px;">)
描画デバイスのOPENを dev.new() でなく、以下の関数で行う事でグラフをファイルに出力する事ができる。
| 関数名 | 説明 | 使用例 |
| pdf | PDFファイルとして出力 | |
| png | PNG画像として出力 | png("plot1.png", width=480, height=480) |
| jpeg | JPEG画像として出力 | |
| bmp | BMP画像として出力 | |
| postscript | PS画像として出力 | |
| pictex | TeXファイルとして出力 | |
|  svg | SVGとして出力 | |
#html(</div>)


トップ   一覧 単語検索 最終更新   ヘルプ   最終更新のRSS