位置:首頁 > 大數據教學 > R語言教學 > R語言箱線圖

R語言箱線圖

箱線圖是分布在一個數據集中的數據的量度。它把組分為三個四分位值的數據。此圖表示的最小值,最大值,中值,第一個四分位數和第三個四分位數中的數據集。在通過拉伸箱圖比較每個跨數據集數據的分布是有用的。

箱線圖是通過使用 R 中的 boxplot()函數來創建。

語法

創建一個箱線圖在 R 中的基本的語法是:

boxplot(x,data,notch,varwidth,names,main)

以下是所使用的參數的說明:

  • x - 是一個向量或一個公式
  • data - 是數據幀
  • notch - 是一個邏輯值。設置為TRUE畫一個缺口
  • varwidth - 是一個邏輯值。設置為 true 時來畫的寬度成正比到樣本大小的方塊。
  • names - 是將每個箱線圖下被打印的組標簽。
  • main - 用於給出曲線圖的標題。

示例

我們使用數據集 “mtcars” 可在R環境中創建一個基本的箱線圖。讓我們來看看在 mtcars 的 "mpg" 和 "cyl" 列。

input <- mtcars[,c('mpg','cyl')]
print(head(input))

當我們上麵的代碼執行時,它產生以下結果:

                   mpg cyl
Mazda RX4         21.0   6
Mazda RX4 Wag     21.0   6
Datsun 710        22.8   4
Hornet 4 Drive    21.4   6
Hornet Sportabout 18.7   8
Valiant           18.1   6

創建箱線圖

下麵的腳本將創建 mpg(英裡每加侖)和cyl(氣缸數)之間的關係的一個箱線圖。

# Give the chart file a name.
png(file = "boxplot.png")

# Plot the chart.
boxplot(mpg ~ cyl, data=mtcars,
                  xlab="Number of Cylinders",
                  ylab="Miles Per Gallon",	
                  main="Mileage Data")

# Save the file.
dev.off()

當我們上麵的代碼執行時,它產生以下結果:

Box Plot using R

箱線圖與缺口

我們可以得到箱線圖與缺口,以了解如何不同類型數據的中位數相互匹配。

下麵腳本將創建為每個數據組的箱線圖與缺口。

# Give the chart file a name.
png(file = "boxplot_with_notch.png")

# Plot the chart.
boxplot(mpg ~ cyl, data=mtcars,
        xlab="Number of Cylinders",
        ylab="Miles Per Gallon",
        main="Mileage Data",
        notch=TRUE,
        varwidth=TRUE,
        col=c("green","yellow","purple"),
        names=c("High","Medium","Low"))

# Save the file.
dev.off()

當我們上麵的代碼執行時,它產生以下結果:

Box Plot with notch using R