Barplot
Before you start: vectors and data frames; row order.
Setup: Use R’s built-in data or the vectors supplied on this page. Run a base plot before adding layers.
Your check: Distinguish counts from supplied summaries and label the category comparison. Practise in the unit summary.
What is a Barplot?
A bar plot compares values across categories. Each separate bar represents a category; its height or length represents a count or another clearly stated summary, such as a total or mean. Use table() when you need counts of observations. Use the supplied numeric values directly when they are already summaries.
For many categories, consider sorting the bars, using horizontal bars, or using a Cleveland dotchart. Connecting unordered categories with lines would imply an order that the data do not have. To show the distribution of a numeric variable in intervals, use a histogram instead.
Create barplots with the barplot(values) function, where values is a vector or matrix.
- If values is a vector, the values determine the heights of the bars in the plot.
- If values is a matrix and the option
beside=FALSEthen each bar of the plot corresponds to a column of height, with the values in the column giving the heights of stacked “sub-bars”. - If height is a matrix and beside=TRUE, then the values in each column are juxtaposed rather than stacked.
- Include option
names.arg=(character vector)to label the bars. - Use
horiz=TRUEto create a horizontal bar plot.
Example with mtcars:
data(mtcars)
counts <- table(mtcars$cyl)
barplot(counts, main="Car Distribution",
xlab="Number of Cylinders")
Simple Horizontal Barplot with Added Labels
counts <- table(mtcars$cyl)
barplot(counts, main="Car Distribution", horiz=TRUE,
names.arg=c("4 Cylinder", "6 Cylinder", "8 Cylinder"))
Stacked Barplot with Colors and Legend
# Stacked Bar Plot with Colors and Legend
counts <- table(mtcars$vs, mtcars$gear)
barplot(counts, main="Car Distribution by Gears and VS",
xlab="Number of Gears", col=c("steelblue","darkgreen"),
legend = rownames(counts))
Grouped and colored Barplot
counts <- table(mtcars$cyl, mtcars$gear)
barplot(counts, main="Car Distribution by Gears and Cylinder",
xlab="Number of Gears", col=c("darkgreen","steelblue", "darkred"),
legend = rownames(counts), beside=TRUE)
Difference between Barplot and Histogram:
Barplots are good when your data is in categories (such as “Comedy”, “Drama”, etc). But when you have continuous data (such as a person’s height) then use a Histogram. It is best to leave gaps between the bars of a Bar Graph, so it doesn’t look like a Histogram.