Barplot in R

ある変数がいくつかの値を取るとき、Rでbarchartやbarplotで表現できる頻度表で情報を要約することが一般的です。 今回は、Rで棒グラフを作成するための基本を解説します。

Rの棒グラフ関数

Rで棒グラフを作成するには、Rの基本関数barplotを使用することができます。 この例では、データフレームから棒グラフを作成することにします。 具体的には、例のデータセットはよく知られているmtcarsです。

# Load datadata(mtcars)attach(mtcars)# Frequency tablemy_table <- table(cyl)my_table
cyl 4 6 811 7 14

Rで棒グラフを作成するには、barplot関数を使用して、以前に作成したテーブルをパラメータとして設定し、データの絶対周波数を表示することができることを思い出してください。 しかし、縦軸にパーセンテージ(相対度数)を表示した棒グラフがお好みなら、prop.table関数を使い、以下のように結果を100倍してください。

# One row, two columnspar(mfrow = c(1, 2))# Absolute frequency barplotbarplot(my_table, main = "Absolute frequency", col = rainbow(3))# Relative frequency barplotbarplot(prop.table(my_table) * 100, main = "Relative frequency (%)", col = rainbow(3))par(mfrow = c(1, 1))

なお、plot関数で因子データで棒グラフを作成することも可能です。

plot(factor(mtcars$cyl), col = rainbow(3))

また、以下のようにtext関数で棒グラフに数字を表示することができます。

barp <- barplot(my_table, col = rainbow(3), ylim = c(0, 15))text(barp, my_table + 0.5, labels = my_table)
変数内に棒グラフを割り当てると、各棒の中心に対応する軸値が格納されるようになりました。

また、grid 関数で棒の後ろにグリッドを追加することもできます。

barp <- barplot(my_table, col = rainbow(3), ylim = c(0, 15))grid(nx = NA, ny = NULL, lwd = 1, lty = 1, col = "gray")barplot(my_table, col = rainbow(3), ylim = c(0, 15), add = TRUE)

Barplot graphical parameters: title, axis labels and colors

他のプロットと同様に、軸ラベル、タイトルや軸のカスタマイズなど幅広いグラフィックパラメータを指定することが可能。 前のコード ブロックでは、col パラメータを使用して棒グラフの色をカスタマイズしました。 ベクターで好みの色を設定したり、rainbow関数で棒グラフの本数をパラメータとして指定したり、他のカラーパレット関数を使用することも可能です。 また、border引数でバーのボーダーカラーを変更できます。

barplot(my_table, # Data main = "Customized bar plot", # Title xlab = "Number of cylinders", # X-axis label ylab = "Frequency", # Y-axis label border = "black", # Bar border colors col = c("darkgrey", "darkblue", "red")) # Bar colors

グループラベルの変更

names.arg引数でそれぞれのグループラベルが変更できます。 この例では、グループのラベルは数字で表示されていますが、次のように変更することができます:

barplot(my_table, names.arg = c("four", "six", "eight")) 

バープロットの幅と棒の間隔

また、widthspace引数を使用して棒の間隔や幅を修正することができます。 グループ間のスペースについては、このチュートリアルの対応するセクションを参照してください。

par(mfrow = c(1, 2))# Bar width (by default: width = 1)barplot(my_table, main = "Change bar width", col = rainbow(3), width = c(0.4, 0.2, 1))# Bar spacebarplot(my_table, main = "Change space between bars", col = rainbow(3), space = c(1, 1.1, 0.1))par(mfrow = c(1, 1))
spaceベクトルは前のバーに対するバーのスペースを表すので、最初のエレメントは考慮されないでしょう。

データフレームまたはリストからの棒グラフ

さらに、データフレームまたは行列の変数で直接棒グラフを作成できますが、変数はいくつかのイベントまたは特性のカウントでなければならないことに注意してください。 次の例では、車の台数を色別にカウントし、棒グラフでプロットしています。

df <- data.frame(carColor = c("red", "green", "white", "blue"), count = c(3, 5, 9, 1))# df <- as.list(df) # Equivalentbarplot(height = df$count, names = df$carColor, col = c("red", "green", "white", "blue"))

連続変数の棒グラフ

連続変数を扱う場合、データを分類するために cut 関数を使用しなければなりません。 そうでない場合、同値でない場合、ベクトルの長さと同じ数の棒があり、棒の高さは1に等しくなります。以下の例では、breaks 引数を使用して、0から45まで5段階でデータを分割します。

x <- c(2.1, 8.6, 3.9, 4.4, 4.0, 3.7, 7.6, 3.1, 5.0, 5.5, 20.2, 1.7, 5.2, 33.7, 9.1, 1.6, 3.1, 5.6, 16.5, 15.8, 5.8, 6.8, 3.3, 40.6)barplot(table(cut(x, breaks = seq(0, 45, by = 5))))

水平バープロット

R でバープロットはデフォルトでは垂直にプロットされます。 しかし、水平方向の棒グラフを表現することはよくあることです。 horiz 引数を TRUE.

barplot(my_table, main = "Barchart", ylab = "Number of cylinders", xlab = "Frequency", horiz = TRUE) # Horizontal barplot

R barplot legend

R の barplot には、legend.text 引数に、凡例を追加したい名称を指定して指定することが可能である。 RStudio では、凡例の背景が透明ではなく白になるため、結果のプロットが若干異なる可能性があることに注意してください。 これは、リスト内のグラフィック・パラメータを設定できる args.legend 引数を使用して実現できます。 位置は top, bottom, topleft, topright, bottomleft, bottomright に設定できます。

barplot(my_table, xlab = "Number of cylinders", col = rainbow(3), legend.text = rownames(my_table), args.legend = list(x = "top"))

同様に、legendfill引数を用いて以下のように、凡例を使った前のプロットが達成できます。

barplot(my_table, xlab = "Number of cylinders", col = rainbow(3))legend("top", legend = rownames(my_table), fill = rainbow(3))

にもかかわらず、この方法は、凡例がそれらの位置でバーと重ならない場合にのみうまく機能します。 より良いアプローチは、バープロットから右側に凡例を移動することです。 これを行うには、次のように args.legend 引数内のリストの要素として渡された inset 引数を設定します。

par(mar = c(5, 5, 4, 10))barplot(my_table, xlab = "Number of cylinders", col = rainbow(3), legend.text = rownames(my_table), # Legend values args.legend = list(x = "topright", inset = c(-0.20, 0))) # Legend arguments

また、垂直および水平棒グラフのそれぞれについて xlim または ylim 引数を使用して軸限界を変更できますが、この場合、指定すべき値が棒の数と幅に依存していることに注意して下さい。 棒グラフを変数に代入すると、各棒の中心に対応する軸点を格納できることを思い出してください。

barplot(my_table, xlab = "Number of cylinders", col = rainbow(3), legend.text = rownames(my_table), xlim = c(0, 4.25))

その他の方法として、layoutparplot.new 関数を使用して棒グラフの下に凡例を移動させることがあります。 この方法は他の方法より高度であり、グラフィカルパラメータが変更されるため、正しいプロットを得るために、コードの実行前にグラフィカルパラメータをクリアする必要があるかもしれません。

# dev.off()# opar <- par(no.readonly = TRUE)plot.new()layout(rbind(1, 2), heights = c(10, 3))barplot(my_table, xlab = "Number of cylinders", col = rainbow(3))par(mar = c(0, 0, 0, 0))plot.new()legend("top", rownames(my_table), lty = 1, col = c("red", "green", "blue"), lwd = c(1, 2))# dev.off()# on.exit(par(opar))

Grouped barplot in R

side by side bar plot や clustered bar chart として知られる grouped barplot は 2 変数以上の R における barplot で、(a) (b) (c) (d) (e) は、(a) (b) (c) (e) (e) (e) (e) (e) のような、(a) と (b) を組み合わせたものです。 チャートは、複数の変数のそれぞれについて棒グラフを表示します。

# Variable am to factoram <- factor(am)# Change factor levelslevels(am) <- c("Automatic", "Manual")# Table cylinder - transmission typeother_table <- table(cyl, am)# other_table <- xtabs(~cyl + am , data = mtcars) # Equivalentbarplot(other_table, main = "Grouped barchart", xlab = "Transmission type", ylab = "Frequency", col = c("darkgrey", "darkblue", "red"), legend.text = rownames(other_table), beside = TRUE) # Grouped bars

もし我々がtable(cyl, am)の代わりにtable(am, cyl)を指定していたら、X軸はトランスミッションの種類の代わりにシリンダーの数を表すことに注意してください。

グループ間のスペース

前に復習しましたが、バー間のスペースを変更することが可能です。

barplot(other_table, main = "Grouped barchart space", xlab = "Transmission type", ylab = "Frequency", col = c("darkgrey", "darkblue", "red"), legend.text = rownames(other_table), beside = TRUE, space = c(0.4, 2.5)) # Space 

グループ内の数値

棒グラフは、一つまたはいくつかの要因で与えられたグループ内の変数を要約するためにも使用することができます。 例えば、車の馬力の平均値に基づいて、シリンダー数とトランスミッションのタイプを表示したいと考える。

summary_data <- tapply(mtcars$hp, list(cylinders = mtcars$cyl, transmission = mtcars$am), FUN = mean, na.rm = TRUE)summary_data
 transmissioncylinders Automatic Manual 4 84.66667 81.8750 6 115.25000 131.6667 8 194.16667 299.5000

ここで、Rで対応する棒グラフを作成します。

par(mar = c(5, 5, 4, 10))barplot(summary_data, xlab = "Transmission type", main = "Horsepower mean", col = rainbow(3), beside = TRUE, legend.text = rownames(summary_data), args.legend = list(title = "Cylinders", x = "topright", inset = c(-0.20, 0)))

Rでのエラーバー付きの棒グラフ

デフォルトではエラーバー付きの棒グラフを作成することはできません。 しかし、次の関数を使用すると、標準のエラーバーを含む完全にカスタマイズ可能な棒グラフを作成できます。

# Arguments:# x: an unique factor object# y: a numeric vector object# ...: additional arguments to be passed to barplot functionbarplot.error <- function(x, y, ...){ mod <- lm(y ~ x) reps <- sqrt(length(y)/length(levels(x))) sem <- sigma(mod)/reps means <- tapply(y, x, mean) upper <- max(means) + sem lev <- levels(x) barpl <- barplot(means, ...) invisible(sapply(1:length(barpl), function(i) arrows(barpl, means + sem, barpl, means - sem, angle = 90, code = 3, length = 0.08)))}# Calling the functionbarplot.error(factor(mtcars$cyl), mtcars$hp, col = rainbow(3), ylim = c(0, 250))

棒グラフにエラーバーを追加することができますが、このシナリオのデータを要約するには、グループ別のボックスプロットがより良いアプローチであると認識されるべきです。

Stacked barplot in R

Stacked bar chart is like a grouped bar graph, but the frequency of the variables are stucked.これは、グループ化された棒グラフのようですが、変数の頻度が積み重ねられます。 このタイプの棒グラフは、引数 beside のデフォルトが FALSE であるように、2つ以上の変数を持つテーブルを引数として渡すとデフォルトで作成されます。

barplot(other_table, main = "Stacked barchart", xlab = "Transmission type", ylab = "Frequency", col = c("darkgrey", "darkblue", "red"), legend.text = rownames(other_table), beside = FALSE) # Stacked bars (default)

stacked bar plot に関連して、 spine plot や mosaic plot など似た実装が存在します。 この種のプロットは graphics パッケージの spineplot および mosaicplot 関数で作成することができます。

モザイクプロットは、2つ以上の量的変数のデータを可視化することができ、それぞれの長方形の面積はそれぞれのグループにおけるその変数の割合を表します。

# install.packages("graphics")library(graphics)mosaicplot(other_table, main = "Mosaic plot")

spineplot はモザイクプロットの特殊なケースであり、stacked barplot の一般化であり、このプロットは、”select” と呼ばれます。 この場合、積み上げ棒グラフとは異なり、それぞれの棒の合計は 1 になります。

spineplot(other_table)

デフォルトでは、前のセクションで作成した積み上げ棒グラフに対して、軸が入れ替わっていることに注意しましょう。

spineplot(t(other_table))

Barplot in R: ggplot2

ggplot2 library は R の有名なグラフィックライブラリですが、データをデータフレーム化したり ggplotgeom_bar 関数を用いて棒グラフを作成することが可能です。 aesの引数には、データフレームの変数名を渡す必要があります。 x にはカテゴリ変数、y には数値変数が入ります。

# install.packages("ggplot2")library(ggplot2)df <- as.data.frame(my_table)ggplot(data = df, aes(x = cyl, y = Freq)) + geom_bar(stat = "identity")

横棒グラフ ggplot2

前の棒グラフを回転させたい場合は以下のようにcoord_flip関数を使ってみてください。

コメントを残す

メールアドレスが公開されることはありません。