使用ggplot2繪圖 (Graphics using ggplot2)


套路2: 使用ggplot2繪圖 (Graphics using ggplot2)

1. 使用時機: 拿到數據時對數據的某些基本特徵及趨勢進行分析了解。

2. 分析類型: 數據基本特性分析。

3. 資料: R內建資料mtcars
使用head函數顯示mtcars前幾排資料
head(mtcars)  # head函數列出mtcars前幾筆資料結果如下

                   mpg cyl disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

4. 安裝繪圖程式套件ggplot2

5. 範例1: 盒圖 (box plot)
library(ggplot2)      # 叫出ggplot2備用
df <- mtcars[, c("mpg","vs")]    # mtcars取出部份資料成為子集
ggplot(df, aes(x = vs, y = mpg, color = vs)) +
  geom_boxplot()
結果:

6. 範例2: 點圖 (dot plot)
library(ggplot2)    # 叫出ggplot2備用
df <- mtcars[, c("mpg","gear")]      # mtcars取出部份資料成為子集
ggplot(df, aes(x = gear, y = mpg, fill = gear)) +
  geom_dotplot(binaxis = 'y', stackdir = 'center', dotsize = 0.5)
結果:

ggplot(df, aes(x = gear, y = mpg, fill = gear)) +
  geom_boxplot(fill="white") +   # 加上boxplot為底
  geom_dotplot(binaxis = 'y', stackdir = 'center', dotsize = 0.5)
結果:

7. 範例3: 分布圖 (density plot)
library(ggplot2)       # 叫出ggplot2備用
df <- mtcars[, c("mpg","vs")]       # mtcars取出部份資料成為子集
ggplot(df, aes(x = mpg, color = vs)) +
  geom_density(size = 1)
結果:

8. 範例4: 直方圖 (histogram)
library(ggplot2)       # 叫出ggplot2備用
df <- mtcars[, c("mpg" ,"vs")]       # mtcars取出部份資料成為子集
ggplot(df, aes(x = mpg)) +
  geom_histogram(binwidth = 5, color = "red", fill = "sky blue")
結果:

9. 範例5: xy散布圖 (scatter plots)
ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point()+  # xy散布點
  geom_smooth(method = lm)   # 回歸線
結果:

10. 範例6: 因子資料 (factor variable) 製作長條圖 (bar chart, bar graph)及大餅圖 (pie chart)
ggplot(mtcars, aes(x = factor(1), fill = factor(cyl))) +
  geom_bar(width = 1)
結果:

ggplot(mtcars, aes(x = factor(1), fill = factor(cyl))) +
  geom_bar(width = 1) +
  coord_polar(theta = "y")  # bar chart polar coordinate變大餅
結果:

11. 範例7: 數值資料製作長條圖 (bar chart, bar graph) 及大餅圖 (pie chart)
第一步: 建立資料
df <- data.frame(
  group = c("MiMi","MaMa","MqMq","MgMg"),
  value = c(12, 23, 35, 30))
第二步: 畫長條圖
ggplot(df, aes(x = group, y = value, fill = group))+
  geom_bar(width = 1, stat = "identity")
結果:

第二步: 畫疊圖
ggplot(df, aes(x = "", y = value, fill = group))+
  geom_bar(width = 1, stat = "identity")
結果:

第三步: polar coordinate變大餅
ggplot(df, aes(x = "", y = value, fill = group))+
  geom_bar(width = 1, stat = "identity") +
  coord_polar("y", start = 0)
結果:

來勁了嗎? 想知道更多?? 補充資料(連結): 關於R繪圖快速入門

留言

這個網誌中的熱門文章

統計不球人 目錄 (Table of Contents)

如何選擇統計方法 1

如何檢查資料是否接近常態分布 (Normality Test using R)