Rの基本プロット:plot、line、bar、pie、histに関する完全チュートリアル
このレッスンでは、Rチュートリアルの「グラフィックス」セクションの最初のトピックであるデータ可視化を取り上げます。Rには、base R (
plot/line/bar) と ggplot2 (ggplot + geom_) の2つのプロットシステムがあります。このレッスンでは、まずbase Rによるプロットについて学びます。これはシンプルで高速なため、データを素早く確認するのに最適です。
このレッスンを修了すると、R を使って 6 種類の基本的なグラフ(散布図、折れ線グラフ、棒グラフ、円グラフ、ヒストグラム、箱ひげ図)を作成できるようになります。
1. 学習内容
- R Basic Graphics System(グラフィックスパッケージ)
- 6種類の基本グラフ:プロット/折れ線/棒グラフ/円グラフ/ヒストグラム/箱ひげ図
- par() のグラフィックパラメータ(色、フォント、レイアウト)
- layout() 複数画像のレイアウト
- ggplot2 との違い(どちらをいつ使うか)
- 実践ガイド:複数のグラフを用いた販売データレポート
2. 営業の可視化に関する話
(1) 課題:この表は直感的に理解しにくい
ボブはマネージャーに第4四半期の売上実績を報告した:
Region Q1 Q2 Q3 Q4
Beijing 1000 1200 1100 1500
Shanghai 1500 1800 1700 2000
Guangzhou 800 900 1000 1200
マネージャーはそれをちらりと見て、「数字なんてどうでもいい。グラフだけくれ」と言った。
(2) Rを用いた解決策
# 1. A Line Chart in One Line of Code(4 Quarterly City Trends) plot(sales, type = "b", col = rainbow(4), main = "Quarterly Sales Trends") # 2. Creating a bar chart in one line(4 Total City Sales) barplot(rowSums(sales[, -1]), main = "Total Sales Comparison", col = "skyblue") # 3. A Line Chart(Percentage) pie(rowSums(sales[, -1]), labels = rownames(sales))
3行のコード → 3つのプロット。Rでの基本的なプロット作成は、これほど迅速です。
3. Rの2つのプロットシステム
(1) 比較
| 特集 | Rの基礎(グラフィックス) | ggplot2 |
|---|---|---|
| 速度 | 極めて高速 (10行) | やや遅い (数十行) |
| 習得のしやすさ | ✅ 簡単 | ❌ 習得に時間がかかる |
| デフォルト、魅力的 | ❌ 基本 | ✅ 出版品質 |
| 柔軟性 | ⚠️ 限定的 | ✅ 非常に柔軟 |
| 適用可能なシナリオ | データの簡易確認 | 刊行物・報告書 |
| 基本的な構文 | 「キャンバスへの描画」 | グラフィックスの文法 |
(2) どちらをいつ使うべきか?
graph TB
A[Imagination Drawing] --> B{Scene}
B -->|Quick Data Overview| C[Basics R plot]
B -->|Published/Report| D[ggplot2]
B -->|Teaching Demonstration| E[Either one is fine]
style A fill:#fff3cd
style C fill:#d4edda
style D fill:#cce5ff
4. plot(): 多彩なプロット(主に散布図)
(1) 基本的な散布図
# Plot a scatter plot of two columns of data
x <- 1:10
y <- x ^ 2
plot(x, y)
(2) 共通パラメータ
plot(x, y,
type = "p", # Graph Type
main = "Title",
xlab = "X Axis",
ylab = "Y Axis",
col = "blue", # Color
pch = 19, # Point-shaped(0-25)
cex = 1.5, # Font Size
xlim = c(0, 12), # X Shaft Range
ylim = c(0, 110)) # Y Shaft Range
(3) 6つのタイプ
| 種類 | 意味 | 目的 |
|---|---|---|
"p" |
ポイント(デフォルト) | 散布図 |
"l" |
線 | 折れ線グラフ |
"b" |
ポイント+ライン | トレンドチャート |
"o" |
線を通る点 | 時系列 |
"h" |
縦線 | 棒グラフ(線グラフ版) |
"s" |
階段 | 階段の図 |
# For the same set of data, 6 A Painting Technique
x <- 1:5
y <- c(2, 4, 3, 5, 4)
par(mfrow = c(2, 3)) # 2 row 3 Column Layout
for (t in c("p", "l", "b", "o", "h", "s")) {
plot(x, y, type = t, main = paste("type =", t))
}
5. 6つの主要チャート
(1) 散布図 plot()
# 4 City Scatter Plot
x <- c(1, 2, 3, 4)
y <- c(1000, 1500, 800, 1200)
plot(x, y,
main = "City Sales Scatter Plot",
xlab = "City Code",
ylab = "Sales",
col = "blue",
pch = 19)
(2) 折れ線グラフの描画(type = "l")
# Quarterly Trend Chart
quarters <- c("Q1", "Q2", "Q3", "Q4")
sales <- c(1000, 1200, 1100, 1500)
plot(quarters, sales,
type = "b", # Point + Line
main = "Q1-Q4 Sales Trends",
xlab = "Quarter",
ylab = "Sales",
col = "darkblue",
lwd = 2, # Line width
pch = 19)
(3) 棒グラフ barplot()
# 4 City Sales Bar Chart
sales_data <- c(Beijing = 4800, Shanghai = 7000, Guangzhou = 3900, Shenzhen = 4500)
barplot(sales_data,
main = "Total Sales by City",
xlab = "City",
ylab = "Sales",
col = c("red", "blue", "green", "orange"),
border = "white",
horiz = FALSE) # TRUE Sideways
(4) 円グラフ pie()
# Sales Share Pie Chart
sales_data <- c(Beijing = 4800, Shanghai = 7000, Guangzhou = 3900, Shenzhen = 4500)
pie(sales_data,
main = "Share of Sales",
col = rainbow(4),
labels = paste0(names(sales_data), "\n", sales_data))
pie()の代わりにgeom_bar()を使用することを推奨しています。
(5) ヒストグラム hist()
# 1000 The Distribution of a Random Number
data <- rnorm(1000, mean = 100, sd = 15)
hist(data,
main = "Normal Distribution",
xlab = "Value",
ylab = "Frequency",
col = "lightblue",
border = "white",
breaks = 30) # min 30 a range
(6) 箱ひげ図 boxplot()
# 4 Class Exam Score Distribution
scores <- list(
1Cls = c(85, 90, 78, 92, 88, 76, 95, 80),
2Cls = c(72, 80, 85, 78, 90, 88, 82, 75),
3Cls = c(95, 88, 92, 90, 85, 78, 80, 88),
4Cls = c(60, 65, 70, 75, 80, 85, 90, 95)
)
boxplot(scores,
main = "4 Class Grade Distribution",
xlab = "Class",
ylab = "Fractions",
col = c("red", "blue", "green", "orange"))
6. par() のグラフパラメータ
(1) クイックリファレンス表
| パラメータ | 機能 | 例 |
|---|---|---|
mfrow |
複数画像のレイアウト(行×列) | par(mfrow = c(2, 2)) |
mar |
マージン(4桁) | par(mar = c(5, 4, 4, 2)) |
bg |
背景色 | par(bg = "lightyellow") |
col |
既定の色 | par(col = "blue") |
cex |
標準の文字サイズ | par(cex = 1.2) |
lty |
実線 | par(lty = 2) 破線 |
pch |
ドット形状 | par(pch = 19) |
(2) 複数画像のレイアウト
# 2x2 Layout par(mfrow = c(2, 2)) plot(1:10, main = "Plot 1") plot(1:10, type = "l", main = "Plot 2") barplot(1:5, main = "Plot 3") pie(1:4, main = "Plot 4") # Restore Default Layout par(mfrow = c(1, 1))
(3) layout() フレキシブルレイアウト
# 1 L + 4 S Layout
layout(matrix(c(1, 1, 2, 3,
1, 1, 4, 5), nrow = 2, byrow = TRUE))
plot(1:10, main = "Large Image") # 1
plot(1:5, main = "Small image 1") # 2
plot(1:5, main = "Small image 2") # 3
plot(1:5, main = "Small image 3") # 4
plot(1:5, main = "Small image 4") # 5
layout(1) # Restore
7. 色と点の形状
(1) 色
# 1. Name
plot(1:5, col = "red")
plot(1:5, col = "blue")
plot(1:5, col = "darkgreen")
# 2. Hexadecimal
plot(1:5, col = "#FF0000")
plot(1:5, col = "#3366CC")
# 3. rainbow() Color Palette
barplot(1:7, col = rainbow(7))
barplot(1:7, col = heat.colors(7))
barplot(1:7, col = topo.colors(7))
barplot(1:7, col = terrain.colors(7))
(2) 点形状 pch
| pch | 形状 | 用途 |
|---|---|---|
| 0–6 | 中空 | さまざまな形状 |
| 19–25 | 良好 | 推奨(クリア) |
| 19 | ドット | 最も一般的 |
| 17 | 三角形 | 強調 |
| 15 | ブロック | バイナリ |
plot(1:25, pch = 0:25, cex = 2)
8. ggplot2との比較
(1) 同じ図形を描く2つの方法
# Data
df <- data.frame(x = 1:5, y = c(2, 4, 3, 5, 4))
# Basics R(5 row)
plot(df$x, df$y, type = "b", main = "Trends", xlab = "X", ylab = "Y",
col = "blue", pch = 19, lwd = 2)
# ggplot2(6 row,By default, it looks better)
library(ggplot2)
ggplot(df, aes(x = x, y = y)) +
geom_line(color = "blue") +
geom_point(color = "blue", size = 3) +
labs(title = "Trends", x = "X", y = "Y") +
theme_minimal()
(2) どちらを選ぶべきか?
| シナリオ | 推奨事項 |
|---|---|
| データの概要 | Rの基本(1行でのプロット) |
| 出版物・論文 | ggplot2(出版レベルの高品質な可視化) |
| チュートリアル | Rの基礎(シンプルでわかりやすい) |
| 標準化レポート | ggplot2(統一テーマ) |
| パラメータの調整 | ggplot2(微調整) |
9. 完全な例:売上データに関するマルチチャートレポート
以下は、このレッスンで取り上げたすべての図を結びつける完全なワークフローの例です。
▶ サンプル:4都市における四半期ごとの売上高の可視化
# ============================================
# 4 Visualization of Quarterly City Sales
# Features:6 Comprehensive Display of Basic Charts
# ============================================
# 1. Prepare data
sales <- matrix(c(
1000, 1200, 1100, 1500, # Beijing
1500, 1800, 1700, 2000, # Shanghai
800, 900, 1000, 1200, # Guangzhou
1200, 1400, 1300, 1600 # Shenzhen
), nrow = 4, byrow = TRUE)
rownames(sales) <- c("Beijing", "Shanghai", "Guangzhou", "Shenzhen")
colnames(sales) <- c("Q1", "Q2", "Q3", "Q4")
print(sales)
# 2. Settings 2x3 Layout
par(mfrow = c(2, 3), mar = c(4, 4, 3, 1))
# 3. Plot 1:Line Chart(4 City)
plot(1:4, sales[1, ], type = "b", col = "red", ylim = c(0, 2500),
main = "Quarterly Sales Trends", xlab = "Quarter", ylab = "Sales",
pch = 19, lwd = 2, xaxt = "n")
axis(1, at = 1:4, labels = colnames(sales))
for (i in 2:4) {
lines(1:4, sales[i, ], type = "b", col = i, pch = 19, lwd = 2)
}
legend("topleft", legend = rownames(sales),
col = 1:4, pch = 19, lwd = 2, cex = 0.7)
# 4. Plot 2:Bar Chart(Total Sales)
barplot(rowSums(sales),
main = "Total Sales by City",
xlab = "City", ylab = "Total Sales",
col = c("red", "blue", "green", "orange"),
border = "white")
# 5. Plot 3:Pie Chart(Percentage)
pie(rowSums(sales),
main = "Share of Sales",
col = rainbow(4),
labels = paste0(rownames(sales), "\n", rowSums(sales)))
# 6. Plot 4:Histogram(Sales Distribution)
hist(sales, main = "Sales Distribution", xlab = "Sales",
col = "lightblue", border = "white", breaks = 10)
# 7. Plot 5:Box-and-Whisker Plot(By City)
boxplot(sales, main = "Quarterly Sales Breakdown by City",
xlab = "City", ylab = "Sales",
col = c("red", "blue", "green", "orange"))
# 8. Plot 6:Stacked Bar Chart
barplot(sales, beside = FALSE, # beside=FALSE → Stacked
main = "Quarterly Sales Stacked Chart",
xlab = "City", ylab = "Sales",
col = c("red", "blue", "green", "orange"),
legend.text = colnames(sales))
# 9. Restore Layout
par(mfrow = c(1, 1))
期待される出力:2×3のグリッドに配置された6つのグラフ(折れ線グラフ、棒グラフ、円グラフ、ヒストグラム、箱ひげ図、積み上げ棒グラフ)。
❓ よくある質問
png() / pdf() / jpeg() などを使用してください:png("myplot.png", width = 800, height = 600)
plot(1:10)
dev.off()
par(family = "PingFang SC")(macOS)または family = "SimHei"(Windows)を追加してください。Linuxの場合は family = "WenQuanYi Zen Hei" を使用してください。ggplot2の場合は theme(text = element_text(family = ...)) を使用してください。par(mfrow = c(row, col)) 均等配置 ② layout(matrix(...)) 柔軟なレイアウト ③ ggplot2のfacet_wrap()を使用してグループ化(より強力)。col lwd pch cex—数十ものパラメータを一つずつ調整しなければならないからです。ggplot2ではtheme()を使用して統一されたスタイルを適用するため、より効率的です。📖 まとめ
- Rには2つのプロットシステムがあります。標準のR(グラフィックス)とggplot2です。
- Rの基本:6つの主要なプロット:plot(散布図)/plot type="l"(折れ線グラフ)/barplot(棒グラフ)/pie(円グラフ)/hist(ヒストグラム)/boxplot(箱ひげ図)
par()グローバルパラメータの設定:mfrow複数の画像 /mar余白 /bg背景 /col色 /pch点のスタイルlayout()フレキシブルレイアウト(大1つ+小4つ)"red"/"#FF0000"/rainbow(n)を使用して色を塗るpng()+dev.off()またはggsave()を使用して画像を保存する- 基本的なRはデータを素早く探索するのに適しており、ggplot2は論文発表などに適しています—両方を学び、必要に応じて使い分けましょう
📝 練習問題
-
基本問題:ベクトル
sales <- c(100, 150, 200, 180, 220)を構築し、type = "p"、"l"、"b"、"h"を用いて 4 つの図形を描き(par(mfrow = c(2, 2))を使用)、4 つの図形の違いを確認する。 -
基本演習:
barplot()を使用して、5つの都市(任意の名前を指定)の販売比較チャートを作成し、4つのパラメータcol = rainbow(5)、main、xlab、およびylabを含めてください。 -
基本演習:
hist()を使用して、rnorm(100, 15)で生成された 1,000 個の乱数のヒストグラムを作成し、パラメータbreaks = 30およびcol = "lightblue"を追加して、その分布が正規分布に近似していることを確認してください。 -
応用演習:生徒10名ずつからなる4つのクラスの成績をシミュレートし(
list()またはdata.frameを使用)、次にboxplot()を使用してクラス4の成績分布図を作成し、色とタイトルを追加してください。 -
課題:ワークフローを完了させてください。4つの製品について4四半期分の売上マトリックスをシミュレートし、
par(mfrow = c(2, 3))を使用して以下の6つのグラフを作成してください:① 傾向を示す折れ線グラフ、② 比較用の棒グラフ、③ 割合を示す円グラフ、④ 分布を示すヒストグラム、⑤ 箱ひげ図、⑥ 積み上げ棒グラフ。最後に、png("report.png", 1200, 800)を使用して、これらを1つの複合グラフとして保存してください。



