R – 统计学
统计学是一种数学分析形式,涉及数据的收集、组织、分析、解释和呈现。统计分析有助于最好地利用现有的大量数据,提高解决方案的效率。
R – 统计
R是一种编程语言,用于环境统计计算和图形。以下是对基本统计概念的介绍,如绘制柱状图、饼状图、柱状图和boxplots等图形。
在这篇文章中,我们将学习为单一变量绘制图表。在R中学习和实现统计学,需要以下软件。
- R软件
- RStudio IDE
R编程语言中统计学中绘制图表的函数
以下是为表示统计数据而绘制图表所需的函数列表。
- plot() 函数: 此函数用于绘制带有坐标轴和标题的散点图。
语法
plot(x, y = NULL, ylim = NULL, xlim = NULL, type = "b" ....)
- data() 函数: 此函数用于加载指定的数据集。
语法
data(list = character(), lib.loc = NULL, package = NULL…..)
- table() 函数: table函数用来建立一个每个因素水平组合的计数的或然率表。
table(x, row.names = NULL, ...)
- barplot() 函数: 它创建了一个带有垂直/水平条的条形图。
语法
barplot(height, width = 1, names.arg = NULL, space = NULL...)
- pie() 函数: 此函数用于创建饼状图。
语法
pie(x, labels = names(x), radius = 0.6, edges = 100, clockwise = TRUE ...)
- hist() 函数: 函数 hist() 为给定的数据值创建一个直方图。
语法
hist(x, breaks = "Sturges", probability = !freq, freq = NULL, ...)
注意: 你可以使用每个函数开头前的”?”符号找到每个函数的信息。
R内置数据集对于开始使用和发展技能非常有用,所以我们将使用一些内置数据集。让我们从使用chickwts数据集创建一个简单的柱状图开始,并学习如何使用数据集和RStudio的一些功能。
柱状图
条形图用矩形条表示分类数据,这些条可以垂直或水平绘制。
# ? is used before a function
# to get help on that function
?plot
?chickwts
data(chickwts) #loading data into workspace
plot(chickwts$feed) # plot feed from chickwts
在上面的代码中,在一个特定的函数前面的’?’意味着它提供了关于该函数的信息和语法。在R中’#’用于注释单行,在R中没有多行注释。这里我们使用 chickwts 作为数据集,feed是数据集中的属性。
输出
feeds=table(chickwts$feed)
# plots graph in decreasing order
barplot(feeds[order(feeds, decreasing=TRUE)])
输出
feeds = table(chickwts$feed)
# outside margins bottom, left, top, right.
par(oma=c(1, 1, 1, 1))
par(mar=c(4, 5, 2, 1))
# las is used orientation of axis labels
barplot(feeds[order(feeds, decreasing=TRUE)]
# horiz is used for bars to be shown as horizontal.
barplot(feeds[order(feeds)], horiz=TRUE,
# col is used for colouring bars.
# xlab is used to label x-axis.
xlab="Number of chicks", las=1 col="yellow")
输出
饼图
饼图是一个圆形的统计图,它被分成几片,以显示数据的不同大小。
data("chickwts")
# main is used to create
# an heading for the chart
d = table(chickwts$feed)
pie(d[order(d, decreasing=TRUE)],
clockwise=TRUE,
main="Pie Chart of feeds from chichwits", )
输出
直方图
直方图是对数据(数字或分类)分布的表示。它类似于柱状图,但它按范围对数据进行分组。
# break is used for number of bins.
data(lynx)
# lynx is a built-in dataset.
lynx
# hist function is used to plot histogram.
hist(lynx)
hist(lynx, break=7, col="green",
main="Histogram of Annual Canadian Lynx Trappings")
输出:
data(lynx)
# if freq=FALSE this will draw normal distribution
lynx
hist(lynx)
hist(lynx, break=7, col="green",
freq=FALSE main="Histogram of Annual Canadian Lynx Trappings")
curve(dnorm(x, mean=mean(lynx),
sd=sd(lynx)), col="red",
lwd=2, add=TRUE)
输出
箱形图
箱形图是一个使用四分位数对数字数据组进行图形化描述的函数。它表示数据的分布,并理解平均值、中位数和方差。
# USJudgeRatings is Built-in Dataset.
?USJudgeRatings
# ylim is used to specify the range.
boxplot(USJudgeRatings$RTEN, horizontal=TRUE,
xlab="Lawyers Rating", notch=TRUE,
ylim=c(0, 10), col="pink")
USJudgeRating是一个有6个属性的Build-in数据集,RTEN是其中的一个属性,即0到10之间的评级。我们用它来绘制一个具有不同属性的boxplot函数的boxplot图。
输出