📜  R直方图

📅  最后修改于: 2021-01-08 09:59:18             🧑  作者: Mango

R直方图

直方图是一种条形图,它显示与一组值范围进行比较的值的数量的频率。直方图用于分布,而条形图用于比较不同实体。在直方图中,每个条形表示给定范围内存在的值的数量的高度。

为了创建直方图,R提供了hist()函数,该函数将向量作为输入并使用更多参数来添加更多功能。 hist()函数具有以下语法:

hist(v,main,xlab,ylab,xlim,ylim,breaks,col,border)

这里,

S.No Parameter Description
1. v It is a vector that contains numeric values.
2. main It indicates the title of the chart.
3. col It is used to set the color of the bars.
4. border It is used to set the border color of each bar.
5. xlab It is used to describe the x-axis.
6. ylab It is used to describe the y-axis.
7. xlim It is used to specify the range of values on the x-axis.
8. ylim It is used to specify the range of values on the y-axis.
9. breaks It is used to mention the width of each bar.

让我们看一个示例,在该示例中,我们借助v,main,col等必需参数创建一个简单的直方图。

# Creating data for the graph.
v <-  c(12,24,16,38,21,13,55,17,39,10,60)

# Giving a name to the chart file.
png(file = "histogram_chart.png")

# Creating the histogram.
hist(v,xlab = "Weight",ylab="Frequency",col = "green",border = "red")

# Saving the file.
dev.off()

输出:

让我们看看更多的示例,在这些示例中,我们使用了hist()函数的不同参数来添加更多功能或创建更具吸引力的图表。

示例:使用xlim和ylim参数

# Creating data for the graph.
v <-  c(12,24,16,38,21,13,55,17,39,10,60)

# Giving a name to the chart file.
png(file = "histogram_chart_lim.png")

# Creating the histogram.
hist(v,xlab = "Weight",ylab="Frequency",col = "green",border = "red",xlim = c(0,40), ylim = c(0,3), breaks = 5)

# Saving the file.
dev.off()

输出:

示例:查找hist()的返回值

# Creating data for the graph.
v <-  c(12,24,16,38,21,13,55,17,39,10,60)

# Giving a name to the chart file.
png(file = "histogram_chart_lim.png")
# Creating the histogram.
m<-hist(v)
m 

输出:

示例:使用text()为标签使用直方图返回值

# Creating data for the graph.
v <-  c(12,24,16,38,21,13,55,17,39,10,60,120,40,70,90)
# Giving a name to the chart file.
png(file = "histogram_return.png")

# Creating the histogram.
m<-hist(v,xlab = "Weight",ylab="Frequency",col = "darkmagenta",border = "pink", breaks = 5)
#Setting labels
text(m$mids,m$counts,labels=m$counts, adj=c(0.5, -0.5))
# Saving the file.
dev.off()

输出:

示例:使用非均匀宽度的直方图

# Creating data for the graph.
v <-  c(12,24,16,38,21,13,55,17,39,10,60,120,40,70,90)
# Giving a name to the chart file.
png(file = "histogram_non_uniform.png")
# Creating the histogram.
hist(v,xlab = "Weight",ylab="Frequency",xlim=c(50,100),col = "darkmagenta",border = "pink", breaks=c(10,55,60,70,75,80,100,120))
# Saving the file.
dev.off()

输出: