直方圖

ggplot2 資料視覺化入門

Rick Scavetta

Founder, Scavetta Academy

常見圖型

圖型 可用幾何(Geom)
散佈圖 points、jitter、abline、smooth、count
長條圖 histogram、bar、col、errorbar
折線圖 line、path
ggplot2 資料視覺化入門

直方圖

ggplot(iris, aes(x = Sepal.Width)) + 
  geom_histogram()
  • 以區間分箱的數值圖。
    • 也就是一種統計函式。
`stat_bin()` using `bins = 30`.
Pick better value with `binwidth`.

ggplot2 資料視覺化入門

預設為 30 個等寬分箱

ggplot(iris, aes(x = Sepal.Width)) + 
  geom_histogram()
  • 以區間分箱的數值圖。
    • 也就是一種統計函式。
# 預設分箱寬度:
diff(range(iris$Sepal.Width))/30
[1] 0.08

ggplot2 資料視覺化入門

直覺又有意義的分箱寬度

ggplot(iris, aes(x = Sepal.Width)) + 
  geom_histogram(binwidth = 0.1)
  • 依資料設定有意義的分箱寬度。

  • 長條之間無空隙。

ggplot2 資料視覺化入門

重新定位刻度

ggplot(iris, aes(x = Sepal.Width)) + 
  geom_histogram(binwidth = 0.1,
                 center = 0.05)
  • 依資料設定有意義的分箱寬度。

  • 長條之間無空隙。

  • X 軸刻度介於長條之間。

ggplot2 資料視覺化入門

不同 Species

ggplot(iris, aes(x = Sepal.Width, 
                 fill = Species)) + 
  geom_histogram(binwidth = .1, 
                 center = 0.05)

ggplot2 資料視覺化入門

預設位置為「stack」

ggplot(iris, aes(x = Sepal.Width,
                 fill = Species)) + 
  geom_histogram(binwidth = .1, 
                 center = 0.05,
                 position = "stack") 

ggplot2 資料視覺化入門

position = 「dodge」

ggplot(iris, aes(x = Sepal.Width, 
                 fill = Species)) + 
  geom_histogram(binwidth = .1, 
                 center = 0.05, 
                 position = "dodge")

ggplot2 資料視覺化入門

position = 「fill」

ggplot(iris, aes(x = Sepal.Width, 
                 fill = Species)) + 
  geom_histogram(binwidth = .1, 
                 center = 0.05, 
                 position = "fill")  

ggplot2 資料視覺化入門

結束投影片

ggplot2 資料視覺化入門

Preparing Video For Download...