R语言条形图

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

语法

在R中创建条形图的基本语法是 –

barplot(H, xlab, ylab, main, names.arg, col)

以下是使用的参数的描述 –

  • H – 是包含条形图中使用的数值的向量或矩阵。
  • xlab – 是x轴的标签。
  • ylab – 是y轴的标签。
  • main – 是条形图的标题。
  • names.arg – 是在每个栏下显示的名称向量。
  • col – 用于给图中的图条给出颜色。

示例

使用输入向量和每个栏的名称创建一个简单的条形图。以下脚本将在当前R工作目录中创建并保存条形图。

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()

当我们执行上述代码时,会产生以下结果 –

《R语言条形图》

条形图标签,标题和颜色

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

示例

以下脚本将在当前R工作目录中创建并保存条形图片,如下所示 –

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()

当我们执行上述代码时,会产生以下结果 –

《R语言条形图》

组条形图和堆叠条形图

我们可以通过使用矩阵作为输入值,在每个栏中创建条形图和条形图。多于两个变量表示为用于创建组条形图和堆叠条形图的矩阵。

setwd("F:/worksp/R")
# Create the input vectors.
colors <- c("green","orange","brown")
months <- c("一月","二月","三月","四月","五月")
regions <- c("东部地区","西部地区","南部地区")

# 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()

当我们执行上述代码时,会产生以下结果 –

《R语言条形图》

        原文作者:R语言教程
        原文地址: https://www.yiibai.com/r/r_bar_charts.html
        本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
    点赞