TExcelTAD
Home › R › R Bars

R Bars

A bar chart compares values across categories, with one bar per category. Base R draws them with barplot():

r · try it yourself
fruit_sales <- c(Apples = 42, Bananas = 58, Cherries = 17, Dates = 9)
barplot(fruit_sales, main = "Fruit sold today", ylab = "Units", col = "goldenrod")
fruit_sales
  Apples  Bananas Cherries    Dates
      42       58       17        9

The names of the vector become the bar labels. Unlike a pie chart, it is easy to see that bananas outsold apples.

Styling bars

Argument Effect
col fill colour(s), recycled across bars
border outline colour (NA for none)
horiz = TRUE horizontal bars
width, space bar width and gap
names.arg labels if the vector has no names
las = 1 / las = 2 horizontal / perpendicular axis labels
r · try it yourself
cities <- c(52.4, 35.1, 28.9, 19.6, 12.3)
barplot(cities, names.arg = c("Tokyo", "Delhi", "Paris", "Cairo", "Lima"),
        horiz = TRUE, las = 1, col = "#276dc3", border = NA,
        main = "Made-up scores", xlab = "Score")
order(cities)
[1] 5 4 3 2 1

Bars from counts

table() counts categories, and barplot() accepts the result directly:

r · try it yourself
gears <- table(mtcars$gear)
gears
barplot(gears, main = "Cars by number of gears", xlab = "Gears",
        ylab = "Count", col = c("tomato", "orange", "gold"))

 3  4  5
15 12  5

Grouped and stacked bars

Give barplot() a matrix to compare several series. Each column becomes a group; by default the rows are stacked. Add beside = TRUE to put them side by side:

r · try it yourself
counts <- table(mtcars$am, mtcars$cyl)
dimnames(counts) <- list(c("automatic", "manual"), c("4 cyl", "6 cyl", "8 cyl"))
counts
par(mfrow = c(1, 2))
barplot(counts, col = c("grey60", "steelblue"), main = "Stacked")
barplot(counts, beside = TRUE, col = c("grey60", "steelblue"),
        main = "Side by side", legend.text = TRUE,
        args.legend = list(x = "topleft", bty = "n"))
          4 cyl 6 cyl 8 cyl
automatic     3     4    12
manual        8     3     2

Ordering bars and adding values

Sorting bars by height makes rankings obvious. barplot() returns the bar midpoints, which you can use to place text:

r · try it yourself
avg_mpg <- tapply(mtcars$mpg, mtcars$cyl, mean)
avg_mpg <- sort(avg_mpg, decreasing = TRUE)
mids <- barplot(avg_mpg, ylim = c(0, 32), col = "seagreen",
                main = "Average MPG by cylinders", xlab = "Cylinders")
text(mids, avg_mpg + 1.5, labels = round(avg_mpg, 1))
round(avg_mpg, 1)
   4    6    8
26.7 19.7 15.1

Test yourself

Which argument draws horizontal bars?

  1. vertical = FALSE
  2. horiz = TRUE
  3. flip = TRUE
  4. las = 1

What does beside = TRUE do with a matrix?

  1. Stacks the rows
  2. Draws grouped bars next to each other
  3. Transposes the matrix
  4. Adds a legend

What does barplot() return (invisibly)?

  1. Nothing
  2. The midpoints of the bars
  3. The colours
  4. A data frame