0
0
R Programmingprogramming~5 mins

Bar plots (geom_bar, geom_col) in R Programming

Choose your learning style9 modes available
Introduction

Bar plots help you see and compare amounts easily using bars. They show how big or small values are in a simple picture.

You want to compare counts of different categories, like favorite fruits.
You have data with values already summed up and want to show those totals.
You want to quickly see which group has the highest or lowest value.
You want to show parts of a whole using bars.
You want a simple visual summary of your data categories.
Syntax
R Programming
ggplot(data) + geom_bar(mapping = aes(x = category))
ggplot(data) + geom_col(mapping = aes(x = category, y = value))

geom_bar() counts the number of cases in each category automatically.

geom_col() uses the values you provide to set bar heights.

Examples
This counts how many cars are in each class and shows bars for each.
R Programming
ggplot(mpg) + geom_bar(aes(x = class))
This uses your own counts to make bars for each fruit.
R Programming
df <- data.frame(fruit = c("apple", "banana", "cherry"), count = c(10, 5, 8))
ggplot(df) + geom_col(aes(x = fruit, y = count))
Sample Program

This program shows two bar plots. The first counts car classes from the mpg dataset. The second shows bars using your own fruit counts.

R Programming
library(ggplot2)

# Using geom_bar to count categories
p1 <- ggplot(mpg) + geom_bar(aes(x = class))

# Using geom_col with your own values
df <- data.frame(
  fruit = c("apple", "banana", "cherry"),
  count = c(10, 5, 8)
)
p2 <- ggplot(df) + geom_col(aes(x = fruit, y = count))

print(p1)
print(p2)
OutputSuccess
Important Notes

geom_bar() is good when you want to count data automatically.

geom_col() is better when you already have numbers to show.

Both create vertical bars by default, but you can flip them with coord_flip().

Summary

Bar plots use bars to compare amounts visually.

geom_bar() counts data for you.

geom_col() uses your own values for bar heights.