Bar plots can be created in R using the barplot() function. We can supply a vector or matrix to this function. If we supply a vector, the plot will have bars with their heights equal to the elements in the vector.
Let us suppose, we have a vector of maximum temperatures (in degree Celsius) for seven days as follows.
max.temp <- c(22, 27, 26, 24, 23, 26, 28)
Now we can make a bar plot out of this data.
Some of the frequently used ones are, main to give the title, xlaband ylabto provide labels for the axes, names.argfor naming each bar, col to define color etc.
We can also plot bars horizontally by providing the argument horiz= TRUE
# barchart with added parameters
barplot(max.temp,
main = "Maximum Temperatures in a Week",
xlab = "Degree Celsius",
ylab = "Day",
names.arg = c("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"),
col = "darkred",
horiz = TRUE)
Sometimes we have to plot the count of each item as bar plots from categorical data. For example, here is a vector of age of 10 college freshmen.
age <- c(17,18,18,17,18,19,18,16,18,18)
Simply doing barplot(age) will not give us the required plot. It will plot 10 bars with height equal to the student’s age. But we want to know the number of student in each age category.
This count can be quickly found using the table() function, as shown below.
table(age)
## age
## 16 17 18 19
## 1 2 6 1
Now plotting this data will give our required bar plot. Note below, that we define the argument density to shade the bars.
barplot(table(age),
main="Age Count of 10 Students",
xlab="Age",
ylab="Count",
border="red",
col="blue",
density=10
)