登录
首页精彩阅读R语言箱线图
R语言箱线图
2017-06-20
收藏

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()

当我们上面的代码执行时,它产生以下结果:

箱线图与缺口

我们可以得到箱线图与缺口,以了解如何不同类型数据的中位数相互匹配。

下面脚本将创建为每个数据组的箱线图与缺口。

# 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()

当我们上面的代码执行时,它产生以下结果:

数据分析咨询请扫描二维码

客服在线
立即咨询