R

R 資料探索與基本繪圖

直方圖(Histograms)

直方圖也是一種很常見的圖形,它可以讓我們看出整個資料大致上的分佈狀況。

base 系統

base 系統上的直方圖可以使用 hist 函數來繪製:

hist(iris$Sepal.Width)

直方圖

預設的狀況下 hist 繪圖時會以資料的頻率作為 y 軸的單位,若要以機率值為單位(總面積和為 1),可以將 freq 參數指定為 FALSE

hist(iris$Sepal.Width, freq = FALSE)

直方圖

hist 預設會使用 Sturges 的方式自動計算 bin 的數目,我們也可以用 breaks 參數自行指定:

hist(iris$Sepal.Width, breaks = 5)

直方圖

甚至也可以指定不等寬的 bins:

hist(iris$Sepal.Width, breaks = c(2, 2.7, 3, 3.5, 4.5))

直方圖

lattice 系統

lattice 系統的直方圖可以使用 histogram 繪製,用法與 base 系統類似,只是改以公式的方式指定資料而已:

histogram(~ Sepal.Width, iris)

直方圖

histogram 的 y 軸單位有三種方式選擇,分別為:percentcountdensity

histogram(~ Sepal.Width, iris, type = "count")

直方圖

breaks 的用法也跟 hist 相同:

histogram(~ Sepal.Width, iris, breaks = 5)

直方圖

ggplot2 系統

ggplot2 系統中直方圖可以使用 geom_histogram 繪製:

ggplot(iris, aes(Sepal.Width)) +
  geom_histogram()

直方圖

bins 可以指定 bin 的數量:

ggplot(iris, aes(Sepal.Width)) +
  geom_histogram(bins = 5)

直方圖

若要改變 y 軸的單位,可以從 aes 的對應關係來指定,可用的參數有 ..count....density..,分別代表次數與密度:

ggplot(iris, aes(x = Sepal.Width, y = ..density..)) +
  geom_histogram(bins = 5)

直方圖

Page: 1 2 3 4 5 6 7

G. T. Wang

個人使用 Linux 經驗長達十餘年,樂於分享各種自由軟體技術與實作文章。

Share
Published by
G. T. Wang

Recent Posts

[開箱] 德國美善品 Thermomix TM6 多功能料理機

本篇是德國美善品 Thermo...

3 年 ago

[開箱] Nokia 215 4G 經典功能型手機

本篇是 Nokia 215 4...

3 年 ago

[開箱] Holy Stone HS210 迷你遙控飛機

本篇是 Holy Stone ...

3 年 ago

[DIY] 用竹子製作吹火筒教學

本篇記錄我用乾燥的竹子製作吹火...

3 年 ago

高鐵會員 TGO 點數兌換商品教學

這裡示範如何線上使用高鐵會員 ...

3 年 ago

Google AdSense 廣告放送量受限問題記錄

這篇是本站的 Google A...

3 年 ago