寫在前面。
很多時候在處理數據前或者出圖前,可能需要先對數據整體情況進行了解。這個時候我們可以用到R基礎繪圖的語句
和ggplot2
完成目標。
接下來,我們分不同的圖形類型
進行啃書學習。
3. 繪制條形圖
如何繪制條形圖?
使用R中的數據集BOD
作為示例數據。
> str(BOD)
'data.frame': 6 obs. of 2 variables:
$ Time : num 1 2 3 4 5 7
$ demand: num 8.3 10.3 19 16 15.6 19.8
- attr(*, "reference")= chr "A1.4, p. 270"
- 使用R基礎繪圖系統
使用barplot()
函數,傳遞兩個參數
,第一個是確定bar
高度的向量;第二個是可選參數
,設定每條bar
對應的標簽。
barplot(BOD$demand, names.arg = BOD$Time)
基礎繪圖系統繪制
有時候,條形圖繪制的是分組數據中元素的頻數,和直方圖類似,不過x
軸是離散取值
。
計算向量中各個類別的頻數,使用table
函數:
> table(mtcars$cyl)
4 6 8
11 7 14
基礎繪圖系統默認繪制的圖形和將上述頻數表傳遞給barplot
為參數繪制的圖形分別如下:
barplot(mtcars$cyl)
基礎繪圖系統默認繪制
barplot(table(mtcars$cyl))
傳遞入頻數表繪制
- 使用ggplot2
> qplot(BOD$Time, BOD$demand, geom = "bar", stat = "identity" )
Error:
! The `stat` argument of `qplot()` was deprecated in ggplot2 2.0.0 and is
now defunct.
Run `rlang::last_trace()` to see where the error occurred.
qplot
默認繪制條形圖
,目前已經被棄用
,我們使用ggplot2
常用的語句形式:
ggplot(data = BOD, aes(Time, demand) ) + geom_bar(stat = "identity")
ggplot2繪制
默認是連續性取值繪制頻數分布,要繪制離散型,只需將向量轉換為因子
。
ggplot(data = mtcars, aes(x = factor(cyl)) ) + geom_bar()
ggplot2繪制的條形圖
以上。