ggplot2パッケージでは、xlim関数などを使用して特に意識をしないで図を作成すると、図の枠線内の描画範囲(軸の範囲)は、その外側にある程度余白を付けて描画される。
> library(ggplot2)
> x <- c(1, 2, 3)
> y <- c(1, 4, 9)
> dtf <- data.frame(x, y)
> g <- ggplot(dtf, aes(x = x, y = y)) + geom_point()
> g <- g + xlim(0, 4) + ylim(0, 10)
> print(g)
特に何も指定しないと描画範囲が横軸がおおよそ-0.1~4.1、縦軸がおおよそ-0.1~10.1となり、指定した範囲きっかりに描画されない。ここでxlim、ylim関数ではなくcoord_cartesian関数を使用して、縦横それぞれの軸の範囲を指定する。
> g <- ggplot(dtf, aes(x = x, y = y)) + geom_point()
> g <- g + coord_cartesian(xlim = c(0, 4), ylim = c(0, 10))
> print(g)
geom_point関数を使う。
> library(ggplot2)
> xd <- c(1, 2, 3, 4, 6)
> yd <- c(1, 4, 9, 16, 36)
> df <- data.frame(xd, yd)
> g <- ggplot(df, aes(x = xd, y = yd)) + geom_point()
> plot(g)
ggplot2パッケージに含まれる関数fortifyを使うと、SpatialLinesDataFrameオブジェクトから座標データを簡単なデータフレーム形式に変換してくれる。以下に、線が20含まれるシェープファイルmap.shpを使用した例を示す。
> library(maptools)
> library(ggplot2)
> shp <- readShapeLines("map.shp")
> shp
(大量にデータが表示される)
> length(shp) # 線の数
[1] 20
> df <- fortify(shp) # データフレーム形式に変換
> is.data.frame(df)
[1] TRUE
> head(df, 3)
long lat order piece group id
1 ・・・
2 ・・・
3 ・・・
> tail(df, 3)
long lat order piece group id
○○ ・・・
○○ ・・・
○○ ・・・
含まれる線の識別は列idを見ればよい。上記の例でいうと、列idは1から始まり線が変わることにidが1ずつ増えて最終行のidは20になる。
演算子「+」を使用して描画オブジェクトを足し合わせればよい。
> library(ggplot2)
> x <- c(1, 2, 3)
> y1 <- c(2, 3, 5)
> y2 <- c(1, 5, 10)
> dtf1 <- data.frame(x = x, y = y1)
> dtf2 <- data.frame(x = x, y = y2)
> g <- ggplot(NULL)
> g <- g + geom_point(data = dtf1, aes(x, y))
> g <- g + geom_point(data = dtf2, aes(x, y))
> print(g)
注意点として、描画処理の最初に「g <- ggplot(NULL)」としてggplot2のオブジェクトを作成しておくことが必要であるので注意。
また、geom_point関数内で「data =」を省くとうまく動作しないのでこちらも注意。
オブジェクトを作成して、それを(明示的に)描画する必要がある。例えば、コマンドラインでの入力では、以下のようにすればグラフは表示される。
> library(ggplot2)
> x <- c(1, 2, 3)
> y <- c(2, 3, 5)
> df <- data.frame(x, y)
> ggplot(df, aes(x, y)) + geom_point()
コマンドラインでは上記の最終行のようにggplotコマンドを使用すれば描画されるが、スクリプト内ではggplotのオブジェクトを作成して、それをprint関数で明示しなければ描画されない。つまり、以下のようにスクリプトファイルを書けばよい。
library(ggplot2)
x <- c(1, 2, 3)
y <- c(2, 3, 5)
df <- data.frame(x, y)
g <- ggplot(df, aes(x, y)) + geom_point()
print(g)
これを以下のように実行すればよい。
> source("test.R")
libraryコマンドを使う。
> library(ggplot2)
Access VBA Anaconda C# Excel Excel VBA Fortran gcc gnuplot Java Microsoft Access Microsoft Excel Octave Open JDK Perl Python Python(Anaconda) Python(テキストマイニング) Python(ファイル・ディレクトリの操作) Python(リスト) Python(変数とオブジェクト) Python(実行とデバッグ) Python(数と式) Python(数学) Python(文字と文字列) Python(環境) Python(行列) Rの操作 R(ggplot2) R(maptools) R(tidyverse) R(その他) R(インターネット) R(グラフィックス) R(セイバーメトリクス) R(データフレーム) R(データベース) R(パッケージ) R(ファイルの入出力) R(ベクトル) R(リスト) R(作図) R(地理空間情報) R(変数とオブジェクト) R(数と式) R(数値計算) R(数学) R(文字と文字列) R(日付と時刻) R(本の計算を再現) R(正規表現) R(演算子と制御構文) R(環境) R(画像) R(統計学) R(統計解析) R(行列) Visual Basic Visual C++