个性化阅读
专注于IT技术分析

R箱图示例图解

本文概述

箱线图是衡量数据在整个数据集中的分布情况的量度。这将数据集分为三个四分位数。该图表示数据集中的最小, 最大, 平均值, 第一四分位数和第三四分位数。在通过为每个数据集绘制一个箱形图来比较数据集中的数据分布时, 箱形图也很有用。

R提供了一个boxplot()函数来创建一个boxplot。 boxplot()函数具有以下语法:

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

这里,

S.No Parameter Description
1. x 它是向量或公式。
2. data 它是数据帧。
3. notch 绘制凹口是设置为true的逻辑值。
4. varwidth 这也是设置为true的逻辑值, 以绘制与样本大小相同的框的宽度。
5. names 这是将在每个箱线图下打印的标签组。
6. main 它用于为图形赋予标​​题。

让我们看一个示例, 以了解如何在R中创建箱形图。在下面的示例中, 我们将使用R环境中存在的” mtcars”数据集。我们将仅使用其两列, 即” mpg”和” cyl”。以下示例将为mpg和cyl之间的关系创建箱形图, 即分别为英里/加仑和汽缸数。

例子

# Giving a name to the chart file.
png(file = "boxplot.png")
# Plotting the chart.
boxplot(mpg ~ cyl, data = mtcars, xlab = "Quantity of Cylinders", ylab = "Miles Per Gallon", main = "R Boxplot Example")

# Save the file.
dev.off()

输出

R箱图示例图解

使用缺口的箱线图

在R中, 我们可以使用一个缺口绘制箱形图。它有助于我们找出不同数据组的中位数如何相互匹配。让我们看一个示例, 以了解如何使用凹口为每个组创建箱线图。

在下面的示例中, 我们将使用相同的数据集” mtcars”。

例子

# Giving a name to our chart.
png(file = "boxplot_using_notch.png")
# Plotting the chart.
boxplot(mpg ~ cyl, data = mtcars, xlab = "Quantity of Cylinders", ylab = "Miles Per Gallon", main = "Boxplot Example", notch = TRUE, varwidth = TRUE, col = c("green", "yellow", "red"), names = c("High", "Medium", "Low")
)
# Saving the file.
dev.off()

输出

R箱图示例图解

小提琴图

R提供了一种附加的绘图方案, 该方案是通过将箱形图和内核密度图结合起来创建的。小提琴图是借助vioplot软件包中提供的vioplot()函数创建的。

让我们看一个例子, 以了解小提琴图的创建。

例子

# Loading the vioplot package 
library(vioplot)
# Giving a name to our chart.
png(file = "vioplot.png")
#Creating data for vioplot function
x1 <- mtcars$mpg[mtcars$cyl==4]
x2 <- mtcars$mpg[mtcars$cyl==6]
x3 <- mtcars$mpg[mtcars$cyl==8]
#Creating vioplot function
vioplot(x1, x2, x3, names=c("4 cyl", "6 cyl", "8 cyl"), col="green")
#Setting title 
title("Violin plot example")
# Saving the file.
dev.off()

输出

R箱图示例图解

Bagplot-二维Boxplot扩展

aplpack软件包中的bagplot(x, y)函数提供了单变量箱线图的两年期版本。该袋子包含所有分数的50%。双变量中位数是近似值。栅栏将自己与外部点分开, 并显示支出。

让我们看一个示例, 以了解如何在R中创建二维箱线图扩展。

例子

# Loading aplpack package
library(aplpack)
# Giving a name to our chart.
png(file = "bagplot.png")
#Creating bagplot function
attach(mtcars)
bagplot(wt, mpg, xlab="Car Weight", ylab="Miles Per Gallon", main="2D Boxplot Extension")
# Saving the file.
dev.off()

输出

R箱图示例图解

赞(0)
未经允许不得转载:srcmini » R箱图示例图解

评论 抢沙发

评论前必须登录!