LoginSignup
4
2

More than 1 year has passed since last update.

【R】散布図を描く方法

Last updated at Posted at 2019-01-28

散布図は、2つの変数の相関関係を表現する方法です。
ごく基本的な作図ですが、度数分布図や箱ひげ図などと並んで良く使われる手法だと思います。

解析に使うデータ

  • 以下のデータは、ある山の東側(east)と西側(west)の様々な標高で測定した樹高(m)です。
    • direction列:斜面の方角(east/west)
    • altitude列:測定地点の標高
    • tree_height列:測定された樹高
tree_height.csv
direction,altitude,tree_height
east,260,12.1
east,320,12.3
east,390,8.2
east,430,9.8
east,470,7.9
east,500,6
west,280,15.3
west,330,11.9
west,380,11.2
west,410,9.3
west,440,7.9
west,500,6.8

データの読み込み

Rのコンソール
> tree_height <- read.table("C:\\tree_height.csv", header=TRUE, encoding="CP932", sep=",")
> tree_height
   direction altitude tree_height
1       east      260        12.1
2       east      320        12.3
3       east      390         8.2
4       east      430         9.8
5       east      470         7.9
6       east      500         6.0
7       west      280        15.3
8       west      330        11.9
9       west      380        11.2
10      west      410         9.3
11      west      440         7.9
12      west      500         6.8

単純な散布図の描画

  • plot(横軸のデータ, 縦軸のデータ)とすることで、簡単に散布図を作成できます。
  • 散布図として表現すると、「標高が上がるにつれて、樹高が低くなっている」ということが一目で分かります。
Rのコンソール
> plot(tree_height$altitude, tree_height$tree_height)

scatter_plot_01.png

散布図のタイトルと軸のラベルを指定する

  • 以下のようにパラメーターを追加することで、タイトルと軸のラベルを指定して散布図を描画することができます。
    • main:グラフのタイトル
    • xlab:横軸のラベル
    • ylab:縦軸のラベル
Rのコンソール
> plot(tree_height$altitude, tree_height$tree_height, main="標高と樹高との関係", xlab="標高(m)", ylab="樹高(m)")

scatter_plot_02.png

グループごとに異なるマーカーで散布図を描画する

  • 「東斜面のデータを白丸(〇)、西斜面のデータを黒丸(●)」というように、データのグループごとに異なるマーカーで表現する時は、以下のように「最初は散布図の枠だけ作っておく」というのがポイントです。
  • 最後に凡例を表示させる必要がありますが、凡例は散布図の描画範囲(枠内)だけでなく、その外側に表示させることもできるようです。
    • 外側に表示させるのは、実際にやったことがないので分かりません...
Rのコンソール
> # type="n"を指定して、散布図の「枠」だけを作成する
> plot(tree_height$altitude, tree_height$tree_height, main="標高と樹高との関係", xlab="標高(m)", ylab="樹高(m)", type="n")
> # 東斜面のデータを白丸(〇)で描画する
> points(tree_height$altitude[tree_height$direction == "east"], tree_height$tree_height[tree_height$direction == "east"], pch = 1)
> # 西斜面のデータを黒丸(●)で描画する
> points(tree_height$altitude[tree_height$direction == "west"], tree_height$tree_height[tree_height$direction == "west"], pch = 16)
> # 散布図の右上に凡例を表示する。
> legend("topright", pch = c(1, 16), legend = levels(tree_height$direction))

scatter_plot_03.png

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2