Learn R Programming  /  Base Graphics  /  Bar Plot

Bar Plot

barplot() draws bars from a numeric vector, most often a table of counts by category — the standard chart for comparing sizes across groups.

A Basic Bar Plot

R Code
sales <- c(Jan = 120, Feb = 150, Mar = 90, Apr = 170)

barplot(sales,
        main = "Monthly Sales",
        col  = "steelblue",
        ylab = "Units Sold")
Output
(a bar chart with 4 bars, one per month)

Bar Plot from a table()

The most common real-world pattern: count how many times each category appears, then plot those counts.

R Code
grades <- c("A","B","A","C","A","B")
counts <- table(grades)
counts

barplot(counts, col = "tomato", main = "Grade Distribution")
Output
grades
A B C 
3 2 1

Horizontal Bars

R Code
barplot(sales, horiz = TRUE, col = "darkgreen", las = 1)

Advanced: Grouped and Stacked Bar Plots

🚀 Advanced Example
A matrix of values, instead of a single vector, produces grouped or stacked bars automatically.
R Code
data <- matrix(c(20,35, 30,25, 40,20), nrow = 2,
               dimnames = list(c("Male","Female"), c("Q1","Q2","Q3")))
data

barplot(data, beside = TRUE, col = c("skyblue","pink"), legend = TRUE) # grouped
barplot(data, beside = FALSE, col = c("skyblue","pink"), legend = TRUE) # stacked
Output
       Q1 Q2 Q3
Male   20 30 40
Female 35 25 20

Key Points

  • barplot() plots a numeric vector of heights, usually built from table().
  • horiz = TRUE flips bars to a horizontal orientation.
  • Passing a matrix instead of a vector automatically enables grouped (beside = TRUE) or stacked bars.