條形圖表示矩形條中的數(shù)據(jù),其長度與變量的值成比例。R使用barplot()函數(shù)來創(chuàng)建條形圖。R可以在條形圖中繪制垂直和水平條。 在條形圖中,每個條可以被賦予不同的顏色。
在R中創(chuàng)建條形圖的基本語法是 -
barplot(H, xlab, ylab, main, names.arg, col)
以下是使用的參數(shù)的描述 -
x軸的標(biāo)簽。y軸的標(biāo)簽。使用輸入向量和每個欄的名稱創(chuàng)建一個簡單的條形圖。以下腳本將在當(dāng)前R工作目錄中創(chuàng)建并保存條形圖。
setwd("F:/worksp/R")
# Create the data for the chart.
H <- c(7,12,28,3,41)
# Give the chart file a name.
png(file = "barchart.png")
# Plot the bar chart.
barplot(H)
# Save the file.
dev.off()
當(dāng)我們執(zhí)行上述代碼時,會產(chǎn)生以下結(jié)果 -

可以通過添加更多參數(shù)來擴(kuò)展條形圖的功能。main參數(shù)用于添加標(biāo)題。 col參數(shù)用于向條添加顏色。 args.name是與輸入向量相同數(shù)量的值的向量,用于描述每個欄的含義。
示例
以下腳本將在當(dāng)前R工作目錄中創(chuàng)建并保存條形圖片,如下所示 -
setwd("F:/worksp/R")
# Create the data for the chart.
H <- c(7,12,28,3,41)
M <- c("一月","二月","三月","四月","五月")
# Give the chart file a name.
png(file = "barchart_months_revenue.png")
# Plot the bar chart.
barplot(H,names.arg = M,xlab = "月份",ylab = "收入量",col = "blue",
main = "收入圖表",border = "red")
# Save the file.
dev.off()
當(dāng)我們執(zhí)行上述代碼時,會產(chǎn)生以下結(jié)果 -

我們可以通過使用矩陣作為輸入值,在每個欄中創(chuàng)建條形圖和條形圖。多于兩個變量表示為用于創(chuàng)建組條形圖和堆疊條形圖的矩陣。
setwd("F:/worksp/R")
# Create the input vectors.
colors <- c("green","orange","brown")
months <- c("一月","二月","三月","四月","五月")
regions <- c("東部地區(qū)","西部地區(qū)","南部地區(qū)")
# Create the matrix of the values.
Values <- matrix(c(2,9,3,11,9,4,8,7,3,12,5,2,8,10,11),nrow = 3,ncol = 5,byrow = TRUE)
# Give the chart file a name.
png(file = "barchart_stacked.png")
# Create the bar chart.
barplot(Values,main = "總收入",names.arg = months,xlab = "月份",ylab = "收入",
col = colors)
# Add the legend to the chart.
legend("topleft", regions, cex = 1.3, fill = colors)
# Save the file.
dev.off()
當(dāng)我們執(zhí)行上述代碼時,會產(chǎn)生以下結(jié)果 -
