直方圖表示一個變量范圍內(nèi)的值的頻率。直方圖類似于條形,但區(qū)別在于將值分組為連續(xù)范圍。直方圖中的每個欄表示該范圍中存在的值的數(shù)量的高度。
R使用hist()函數(shù)創(chuàng)建直方圖。 該函數(shù)將一個向量作為輸入,并使用一些更多的參數(shù)繪制直方圖。
使用R創(chuàng)建直方圖的基本語法是 -
hist(v,main,xlab,xlim,ylim,breaks,col,border)
以下是使用的參數(shù)的描述 -
x軸。x軸上的值范圍。y軸上的值范圍。使用輸入向量,標(biāo)簽,列和邊界參數(shù)創(chuàng)建一個簡單的直方圖。下面給出的腳本將創(chuàng)建并保存當(dāng)前R工作目錄中的直方圖。
setwd("F:/worksp/R")
# Create data for the graph.
v <- c(9,13,21,8,36,22,12,41,31,33,19)
# Give the chart file a name.
png(file = "histogram.png")
# Create the histogram.
hist(v, main="直方圖示例",xlab = "重量", ylab="高度",col = "yellow",border = "blue")
# Save the file.
dev.off()
當(dāng)我們執(zhí)行上述代碼時,會產(chǎn)生以下結(jié)果 -

要指定X軸和Y軸允許的值的范圍,可以使用xlim和ylim參數(shù)。
每個條的寬度可以通過使用斷點來決定。參考如下代碼 -
setwd("F:/worksp/R")
# Create data for the graph.
v <- c(9,13,21,8,36,22,12,41,31,33,19)
# Give the chart file a name.
png(file = "histogram_lim_breaks.png")
# Create the histogram.
hist(v, main="直方圖示例-2", xlab = "重量", ylab="高度",col = "green",border = "red", xlim = c(0,40), ylim = c(0,5),
breaks = 5)
# Save the file.
dev.off()
當(dāng)我們執(zhí)行上述代碼時,會產(chǎn)生以下結(jié)果 -
