May 12, 2021 R language tutorial
A bar chart represents the data in a rectangular bar, the length of which is proportional to the value of a variable. T he R language uses the function barplot() to create a bar chart. T he R language can draw vertical and horizontal bars in a bar chart. I n a bar chart, each bar can be given a different color.
The basic syntax for creating a bar chart in the R language is -
barplot(H, xlab, ylab, main, names.arg, col)
The following is a description of the parameters used -
H is a vector or matrix of values contained in a bar chart.
xlab is the label for the x-axis.
ylab is the label for the y-axis.
Main is the title of the bar chart.
names.arg is a vector of names that appear under each bar.
col is used to provide color to the bars in the figure.
Create a simple bar chart using the input vector and the name of each bar.
The following script creates and saves a bar chart in the current R-language working directory.
# 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()
When we execute the code above, it produces the following results -
You can extend the functionality of the bar chart by adding more parameters. T he main parameters are used to add a title. T he col parameter is used to add color to the bar. n ame.args is a vector that has the same number of values as the input vector to describe the meaning of each bar.
The following script creates and saves a bar chart in the current R language working directory.
# 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()
When we execute the code above, it produces the following results -
We can use the matrix as an input value to create bar charts and stacked groups of bars in each bar.
More than two variables are represented as a matrix for creating a combined bar chart and a stacked bar chart.
# 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()