+4 votes
in Programming Languages by (40.5k points)
I have the following two vectors. I want to visualize them using a bar chart. The bars for 'a' and 'b' should be side-by-side and in different colors. How can I generate a bar graph in R?

a <- c(10,15,20,12,16,18,17)

b <- c(12,14,23,10,13,19,18)

1 Answer

+1 vote
by (349k points)
selected by
 
Best answer

There is a barplot() function in R; you can use it to generate a side-by-side bar plot. You need to create a matrix using two vectors for the plot.

Here is an example using your vectors 'a' and 'b'. I created a matrix 'm' with 2 columns ('a' and 'b') and then transposed it to make it a 10-column matrix. Each column has values from 'a' and 'b'.

a <- c(10,15,20,12,16,18,17)
b <- c(12,14,23,10,13,19,18)
m <- t(matrix(c(a,b), nc=2))
barplot(m, beside = TRUE,  col = c("blue", "red"), main = "Bar plot example", ylab = "value")
legend("topleft", c("a", "b"), pch = 15, col = c("blue", "red"), bty = "n")

The matrix 'm' looks like the following:

> m
     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]   10   15   20   12   16   18   17
[2,]   12   14   23   10   13   19   18

The above code generates the following bar plot:

Bar plot using R

Related questions

+1 vote
1 answer
+2 votes
1 answer
+3 votes
1 answer
+3 votes
1 answer

...