寫在前面。
很多時候在處理數據前或者出圖前,可能需要先對數據整體情況進行了解。這個時候我們可以用到R基礎繪圖的語句
和ggplot2
完成目標。
接下來,我們分不同的圖形類型
進行啃書學習。
5. 繪制箱線圖
如何繪制箱線圖對不同分布進行比較?
使用ToothGrowth
數據集作為示例數據:
> str(ToothGrowth)
'data.frame': 60 obs. of 3 variables:
$ len : num 4.2 11.5 7.3 5.8 6.4 10 11.2 11.2 5.2 7 ...
$ supp: Factor w/ 2 levels "OJ","VC": 2 2 2 2 2 2 2 2 2 2 ...
$ dose: num 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 ...
- 使用R基礎繪圖系統
當傳遞給plot
函數的x
為因子型變量
時(與數值型變量對應),會繪制箱線圖。
plot(ToothGrowth$supp, ToothGrowth$len)
基礎繪圖系統繪制
當兩個向量在一個數據集,可以使用公式語法
:
boxplot( len~ supp, data = ToothGrowth)
在x
軸使用兩個變量交互:
boxplot( len~ supp + dose, data = ToothGrowth)
基礎繪圖系統繪制
- 使用ggplot2的
qplot
函數
添加參數geom = "boxplot"
:
qplot(ToothGrowth$supp, ToothGrowth$len, geom = "boxplot")
ggplot2繪制
向量在同一數據集時,也可以使用如下語句,是等價的:
qplot(supp, len, data = ToothGrowth, geom = "boxplot")
dev.off()
ggplot(ToothGrowth , aes(supp, len )) + geom_boxplot()
使用interaction
選項將分組變量組合在一起繪制多分組箱線圖
,如果所需數據均在一個數據集下,下面的語句都是等價的:
qplot( interaction(ToothGrowth$supp, ToothGrowth$dose) , ToothGrowth$len, geom = "boxplot")
dev.off()
qplot( interaction(supp, dose), len, data = ToothGrowth, geom = "boxplot")
dev.off()
ggplot(ToothGrowth , aes(interaction(supp, dose), len )) + geom_boxplot()
都會產生如下數據結果:
qplot繪制
以上。