R barplot() function - Drawing bar charts
The R barplot() function is used to create bar charts, suitable for displaying comparisons of categorical data.
The height of bars represents the magnitude of values, commonly used for comparison among categories.
The syntax format of the barplot() function is as follows:
barplot(height, names.arg = NULL, col = NULL,
main = "", xlab = "", ylab = "", horiz = FALSE)
Parameter description:
heightA vector or matrix of bar heights.
names.argLabels below each bar.
horizWhether to draw a horizontal bar chart.
Example
# Product sales data
products <- c("Product A", "Product B", "Product C", "Product D", "Product E")
sales <- c(120, 85, 150, 90, 110)
# Vertical bar chart
barplot(sales,
names.arg = products,
main = "Sales volume of each product",
xlab = "Product",
ylab = "Sales volume",
col = c("steelblue", "coral", "seagreen",
"gold", "purple"))
products <- c("Product A", "Product B", "Product C", "Product D", "Product E")
sales <- c(120, 85, 150, 90, 110)
# Vertical bar chart
barplot(sales,
names.arg = products,
main = "Sales volume of each product",
xlab = "Product",
ylab = "Sales volume",
col = c("steelblue", "coral", "seagreen",
"gold", "purple"))
Running the above code will display a colored bar chart comparing the sales volume of each product.
barplot() can also draw grouped bar charts:
Example
# Grouped data: comparison of sales in two quarters
quarter_data <- matrix(c(120, 85, 150, 90, 110,
130, 90, 140, 95, 125),
nrow = 2, byrow = TRUE)
rownames(quarter_data) <- c("Q1", "Q2")
colnames(quarter_data) <- c("A", "B", "C", "D", "E")
# Grouped bar chart
barplot(quarter_data,
beside = TRUE,
legend = rownames(quarter_data),
main = "Comparison of product sales by quarter",
col = c("steelblue", "coral"))
quarter_data <- matrix(c(120, 85, 150, 90, 110,
130, 90, 140, 95, 125),
nrow = 2, byrow = TRUE)
rownames(quarter_data) <- c("Q1", "Q2")
colnames(quarter_data) <- c("A", "B", "C", "D", "E")
# Grouped bar chart
barplot(quarter_data,
beside = TRUE,
legend = rownames(quarter_data),
main = "Comparison of product sales by quarter",
col = c("steelblue", "coral"))
Running the above code will display a grouped comparison chart of product sales in two quarters.
Other extensions
R language example