R教程

R 条形图

条形图以矩形条的形式表示数据,条的长度与变量的值成正比。 R 使用函数 barplot() 创建条形图。 R 可以在条形图中绘制垂直条和水平条。在条形图中,每个条形都可以被赋予不同的颜色。

语法

在 R 中创建条形图的基本语法是-
barplot(H,xlab,ylab,main, names.arg,col)
以下是所用参数的说明-
H 是包含条形图中使用的数值的向量或矩阵。 xlab 是 x 轴的标签。 ylab 是 y 轴的标签。 main 是条形图的标题。 names.arg 是出现在每个条形下方的名称向量。 col 用于为图表中的条形赋予颜色。

示例

仅使用输入向量和每个条形的名称即可创建一个简单的条形图。
下面的脚本将在当前 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()
当我们执行上面的代码时,它会产生以下结果-
使用 R 的条形图

条形图标签、标题和颜色

可以通过添加更多参数来扩展条形图的功能。 main 参数用于添加 titlecol 参数用于为条形添加颜色。 args.name 是一个与输入向量具有相同数量值的向量,用于描述每个条的含义。

示例

以下脚本将在当前 R 工作目录中创建和保存条形图。
# Create the data for the chart
H <-c(7,12,28,3,41)
M <-c("Mar","Apr","May","Jun","Jul")
# Give the chart file a name
png(file = "barchart_months_revenue.png")
# Plot the bar chart 
barplot(H,names.arg=M,xlab="Month",ylab="Revenue",col="blue",
main="Revenue chart",border="red")
# Save the file
dev.off()
当我们执行上面的代码时,它会产生以下结果-
带有标题的条形图使用 R

分组条形图和堆积条形图

我们可以通过使用矩阵作为输入值来创建条形图,其中包含条形组和每个条形中的堆栈。
两个以上的变量表示为一个矩阵,用于创建分组条形图和堆积条形图。
# Create the input vectors.
colors = c("green","orange","brown")
months <-c("Mar","Apr","May","Jun","Jul")
regions <-c("East","West","North")
# 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 = "total revenue", names.arg = months, xlab = "month", ylab = "revenue", col = colors)
# Add the legend to the chart
legend("topleft", regions, cex = 1.3, fill = colors)
# Save the file
dev.off()
使用 R 的堆积条形图
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4