R – Matrix as Bar Plot

To draw matrix as bar plot in R, call barplot() function and pass the matrix as height parameter.

In this tutorial, we will learn how to draw a Bar Plot from Matrix Data in R, using barplot() function.

Examples

In the following program, we will take a matrix A, and draw this matrix as bar plot.

example.R

</>
Copy
A <- matrix(c(2, 4, 7, 5), ncol = 2)
barplot(A)

Matrix A

     [,1] [,2]
[1,]    2    7
[2,]    4    5

Output

R - Matrix as Bar Plot

The matrix columns are read from top to bottom and the bars are drawn from bottom to top as in a stack.

Now, let us take a matrix A with 3 rows and 4 columns, and draw a bar plot from this matrix.

example.R

</>
Copy
A <- matrix(c(2, 4, 7, 5, 10, 1, 5, 3, 4, 2, 1, 17), ncol = 4)
barplot(A)

Matrix A

     [,1] [,2] [,3] [,4]
[1,]    2    5    5    2
[2,]    4   10    3    1
[3,]    7    1    4   17

Output

R - Matrix as Bar Plot

Conclusion

In this R Tutorial, we learned how to draw Bar Plots from a Matrix in R using barplot() function, with the help of examples.