R语言 柱状图
柱状图是一种数据的图形表示,它用高度或长度与所代表的数值成正比的矩形条来表示分类数据。换句话说,它是数据集的象形表示法。这些数据集包含代表长度或高度的变量的数值。
R 使用函数 barplot() 来创建条形图。在这里,垂直和水平条形图都可以绘制。
语法
barplot(H, xlab, ylab, main, names.arg, col)
参数
- H: 该参数是一个包含数值的向量或矩阵,在柱状图中使用。
- xlab: 该参数是柱状图中X轴的标签。
- ylab: 该参数是柱状图中y轴的标签。
- main: 该参数是柱状图的标题。
- names.arg: 这个参数是条形图中每个条形下出现的名称的向量。
- col: 该参数用于为图表中的条形图提供颜色。
创建一个简单的条形图
方法: 为了创建一个条形图。
- 一个向量( **H <- c(Values **…))包含要使用的数字值。
- 这个向量 H 用 barplot() 来绘制 。
例子
# Create the data for the chart
A <- c(17, 32, 8, 53, 1)
# Plot the bar chart
barplot(A, xlab = "X-axis", ylab = "Y-axis", main ="Bar-Chart")
输出:
创建一个水平条形图
方法: 创建一个水平条形图。
- 取出制作简单条形图所需的所有参数。
- 现在为了使它成为水平的,加入了新的参数。
barplot(A, horiz=TRUE )
例子: 创建一个水平条形图
# Create the data for the chart
A <- c(17, 32, 8, 53, 1)
# Plot the bar chart
barplot(A, horiz = TRUE, xlab = "X-axis",
ylab = "Y-axis", main ="Bar-Chart")
输出:
在条形图中添加标签、标题和颜色
标签、标题和颜色是柱状图中的一些属性,可以通过添加和传递一个参数来添加到柱状图中。
方法
- 要在柱状图中添加标题。
barplot( A, main = title_name )
- X轴和Y轴可以在柱状图中进行标注。要在柱状图中添加标签。
barplot( A, xlab= x_label_name, ylab= y_label_name)
- 要在柱状图中添加颜色。
barplot( A, col=color_name)
例子 :
# Create the data for the chart
A <- c(17, 2, 8, 13, 1, 22)
B <- c("Jan", "feb", "Mar", "Apr", "May", "Jun")
# Plot the bar chart
barplot(A, names.arg = B, xlab ="Month",
ylab ="Articles", col ="green",
main ="GeeksforGeeks-Article chart")
输出:
创建堆叠式和分组式条形图
条形图可以用条形组和堆叠两种形式表示。
方法
- 取一个向量值并将其制成矩阵M,以便进行分组或堆叠。矩阵的制作可以通过以下方式完成。
M <- matrix(c(values...), nrow = no_of_rows, ncol = no_of_column, byrow = TRUE)
- 为了明确地显示条形图,我们可以使用beside参数。
barplot( beside=TRUE )
例1 :
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)
# Create the bar chart
barplot(Values, main = "Total Revenue", names.arg = months,
xlab = "Month", ylab = "Revenue",
col = colors, beside = TRUE)
# Add the legend to the chart
legend("topleft", regions, cex = 0.7, fill = colors)
输出:
例2 :
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)
# 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 = 0.7, fill = colors)
输出: