R(作図)

2025年1月17日 (金)

[R]作図の色指定で使える色を虹色のグラデーションで得る

rainbow関数を使う。引数に整数を指定するとその数だけ、赤→紫の方向にグラデーションで順番に色を返す。以下は引数に7を指定した例。戻り値は7色になる。

> par_mai_old <- par("mai")
> par(mai = c(0.1, 1.5, 0.1, 0.1))
> n <- 7
> s <- rainbow(n)
> print(s)
[1] "#FF0000" "#FFDB00" "#49FF00" "#00FF92" "#0092FF" "#4900FF" "#FF00DB"
> barplot(rep(1, n), names = s, col = s, horiz = TRUE, las = 1, xaxt = "n")
> par(mai = par_mai_old)

R_rainbow_barplot1

以下は14を指定した例。赤から始まり紫までグラデーションで色が戻る。

> par_mai_old <- par("mai")
> par(mai = c(0.1, 1.5, 0.1, 0.1))
> n <- 14
> s <- rainbow(n)
> print(s)
[1] "#FF0000" "#FF6D00" "#FFDB00" "#B6FF00" "#49FF00" "#00FF24" "#00FF92"
[8] "#00FFFF" "#0092FF" "#0024FF" "#4900FF" "#B600FF" "#FF00DB" "#FF006D"
> barplot(rep(1, n), names = s, col = s, horiz = TRUE, las = 1, xaxt = "n")
> par(mai = par_mai_old)

R_rainbow_barplot2

2025年1月 7日 (火)

[R]作図の色指定で使える色名を画面表示する

colors関数とbarplot関数を組み合わせると、作図機能を使って簡単に一覧表示することができる。以下は、1~20番目の色名とその色を図示したもの。


> par_mai_old <- par("mai")
> par(mai = c(0.1, 1.5, 0.1, 0.1))
> n <- 1:20
> s <- colors()[n]
> barplot(rep(1, length(n)), names = s, col = s, horiz = TRUE, las = 1, xaxt = "n")
> par(mai = par_mai_old)

R_colors

2025年1月 5日 (日)

[R]作図の色指定で使える色名を調べる

colors関数かcolours関数を使う。この関数は中身は同じで、色指定で使える色名を文字列型ベクトルで返す。

> colors()
[1] "white" "aliceblue" "antiquewhite"
[4] "antiquewhite1" "antiquewhite2" "antiquewhite3"
[7] "antiquewhite4" "aquamarine" "aquamarine1"
(以下省略)
> length(colors())
[1] 657
> colors()[1:3]
[1] "white" "aliceblue" "antiquewhite"

2023年10月 5日 (木)

[R]2次元線図を描画後にそれぞれの軸方向の描画範囲を得る

par関数に"usr"パラメーターを指定して実行する。実行すると数値型ベクトルで(横軸方向左端、横軸方向右端、縦軸方向下端、縦軸方向上端)の値を返す。以下、実行例。

> x <- 1:10
> y <- log(x)
> plot(x, y)
> par("usr")
[1] 0.6400000 10.3600000 -0.0921034 2.3946885
> plot(x, y, asp = 1.0)
> par("usr")
[1] 0.640000 10.360000 -3.202457 5.505042
> plot(x, y, asp = 1.0, xaxs = "i", yaxs = "i")
> par("usr")
[1] 1.000000 10.000000 -2.879957 5.182542

Par_usr_03Par_usr_02Par_usr_01

plot関数はaspオプションを指定しないと、与えたプロット点に応じてアスペクト比が決まり描画範囲も決まる。例えばaspオプションに1を与えると、描画範囲が短いほうの軸はアスペクト比に応じて強制的に描画範囲が伸ばされる。上の2番目の例では縦軸方向の描画範囲が伸ばされている。

xaxsとyaxsオプションを指定しないと(デフォルトの"r")、それぞれのプロット点による描画範囲の4%だけ、両方向に描画範囲が広がる(横軸であれば10-1=9より9×0.04=0.36なので、左端は1-0.36=0.64)。この描画範囲を与えたプロット点の範囲ぴったりにしたい場合は、xaxsとyaxsオプションにそれぞれ"i"を与えればよい。上の3番目の例では、図もpar関数の戻り値もそのようになっている。