棒グラフは複数のカテゴリー間で数(例数、個数、値)を比べるときに用いられます。

データ例
赤が15、青が20、黄色が10という実験群のデータと
赤が5、青が30、黄色が15という対照群のデータがあるとしましょう。
まず、データを代入します。
x <- cbind(c(15, 20, 30), c(5, 30, 15))
それぞれの名称もつけておきましょう。
colnames(x) <- c("experiment", "control")
rownames(x) <- c("red", "blue", "yellow")
x
このデータの棒グラフを作ります。
barplot(x)

グラフを横に並べたいときは、beside=Tを付け足します。
barplot(x, beside=T)

値を比べるときも同じ手順でできです。
今度は、cbindではなくrbindを使いましょう。
x2 <- rbind(c(12.3, 4.5, 8.2, 4.2), c(15.5, 5.2, 8.5, 6.3))
x2
colnames(x2) <- c("A", "B", "C", "D")
rownames(x2) <- c("Exp", "Control")
x2
barplot(x2)
グラフを横に並べたいときは、beside=Tを付け足します。
barplot(x2, beside=T)

凡例の表示や色の指定
このままだと情報不足で分かりにくいので、凡例を表示します。
簡単に表示する場合は凡例legendをTRUEにします。
barplot(x, legend=T) 
legendを独自に設定して付け足すこともできます。
barplot(x)
legend(2, 65, c("Red", "Blue", "Yellow"), pch=15, col=c("gray20", "gray50", "gray80"), pt.cex=2, cex=1.2)
legend(2, 65, c("Red", "Blue", "Yellow"), pch=0, pt.cex=2, cex=1.2)

色を付けるならば、colで色を指定します。
barplot(x, legend=T, beside=T, col=c("red", "blue", "yellow"))
これでは美しくないと感じる人は、「原色大辞典」というウェブページを利用しましょう。
「原色大辞典」には、色見本と16進数の表記が掲載されています。
barplot(x, legend=T, beside=T, col=c("#e95464", "#007bbb", "#e6b422"))

最後に、xの行と列を入れ替えます。t(x)とします。xとt(x)を比べると
x
t(x)
t(x) を使うと、X軸を色でまとめることになります。
barplot(t(x), beside=T)
legend(1, 25, c("Experiment", "Control"), pch=15, cex=1.5, pt.cex=2, col=c("gray80", "gray20"))
legend(1, 25, c("Experiment", "Control"), pch=0, cex=1.5, pt.cex=2)

Diperbaharui kali terakhir: Selasa, 16 Februari 2021, 9:08 PM