ggplot2 Tutorial

Create clear, publication-ready charts with ggplot2

Scatter plots, bar charts, histograms, boxplots and more — plus themes, labels and exporting for reports.

ggplot2 cheat sheet Get help with your graphs

Bar Charts in ggplot2: A Complete Guide with Examples

Updated

Create clear, colourful bar charts in R with ggplot2. Learn when to use geom_bar() and geom_col(), then build count, summary, grouped, stacked, 100% stacked, horizontal and labelled charts with practical examples and downloadable data.

This lesson is part of the ggplot2 tutorial. The R examples use the built-in mpg dataset where possible. Additional downloadable CSV files are included for grouped, stacked and summary bar chart exercises.

1. What is a bar chart in ggplot2?

A bar chart uses rectangular bars to compare values across categories. The length or height of each bar represents a quantity such as a count, total, average, percentage or rate. Bar charts are useful when the variable on one axis is categorical and the other axis contains a numerical value.

For example, you could compare the number of cars in each vehicle class, average sales by region, student enrolments by programme, or the percentage of customers using different payment channels.

Important distinction: use geom_bar() when you want ggplot2 to count the observations. Use geom_col() when your data already contain the heights you want to display.

Common types of bar charts

  • Simple/count bar chart: one bar for each category.
  • Summary bar chart: displays an existing value, such as average sales.
  • Grouped bar chart: places subgroup bars side by side.
  • Stacked bar chart: stacks subgroup values within each category.
  • 100% stacked bar chart: compares subgroup proportions.
  • Horizontal bar chart: displays bars from left to right.
  • Faceted bar chart: creates separate panels for groups.
  • Bar chart with labels or error bars: adds exact values or uncertainty information.

2. Prepare your data and load ggplot2

Install ggplot2 once if it is not already installed. Load it at the start of each new R session.

install.packages("ggplot2")  # Run once
library(ggplot2)

Use the built-in mpg dataset

The mpg dataset is supplied with ggplot2. It contains vehicle characteristics, including vehicle class, drivetrain and fuel economy. We will use class for categories and drv for drivetrain groups.

data("mpg")

head(mpg)
str(mpg)
table(mpg$class)
table(mpg$class, mpg$drv)

For bar charts, check whether your category is stored as a factor or character and whether your numeric variable is actually numeric.

Example practice data

The downloadable practice files use a small fictional sales dataset. They are intended for learning the chart syntax and are not real business results.

counts <- read.csv("category_counts.csv")
sales  <- read.csv("quarterly_sales.csv")
mix    <- read.csv("sales_mix.csv")

head(counts)
head(sales)
head(mix)

3. Count observations with geom_bar()

geom_bar() uses stat = "count" by default. It counts how many rows belong to each category and draws a bar with that height. You do not need to calculate the frequencies first.

Step 1: provide the data frame and map the category to the x-axis.
Step 2: add geom_bar() to count rows in each category.
Step 3: add a title and meaningful axis labels.
ggplot(mpg, aes(x = class)) +
  geom_bar(fill = "#4361EE", colour = "white") +
  labs(
    title = "Number of vehicles by class",
    x = "Vehicle class",
    y = "Number of vehicles"
  ) +
  theme_minimal()
Colourful ggplot2-style bar chart showing counts across six vehicle categories
Count bar chart example. The supplied R code uses the real built-in mpg dataset; the preview is a separate practice illustration.

Change the bar colour

Use fill outside aes() to give every bar one fixed colour. Use colour to change the bar outline.

# One colour for all bars
ggplot(mpg, aes(class)) +
  geom_bar(fill = "cornflowerblue", colour = "white")

# Map fill to the category to give categories different colours
ggplot(mpg, aes(class, fill = class)) +
  geom_bar(show.legend = FALSE) +
  scale_fill_brewer(palette = "Set2")

Count categories in descending order

library(forcats)

ggplot(mpg, aes(x = fct_infreq(class), fill = class)) +
  geom_bar(show.legend = FALSE) +
  labs(x = "Vehicle class", y = "Count") +
  theme_minimal()

4. Use geom_col() for values already calculated

Use geom_col() when each row already contains a value to plot. Unlike geom_bar(), it does not count the rows to determine bar height. The default statistic is identity.

Example: calculate average highway fuel economy

library(dplyr)

class_summary <- mpg |>
  group_by(class) |>
  summarise(
    mean_hwy = mean(hwy, na.rm = TRUE),
    .groups = "drop"
  )

ggplot(class_summary, aes(x = class, y = mean_hwy, fill = class)) +
  geom_col(show.legend = FALSE, width = 0.75) +
  labs(
    title = "Average highway fuel economy by vehicle class",
    x = "Vehicle class",
    y = "Mean highway MPG"
  ) +
  scale_fill_brewer(palette = "Set2") +
  theme_minimal()
Bar chart of pre-calculated numerical values using the geom_col approach
Example of plotting existing values. Use geom_col() when y is already present in your summary data.

geom_bar() versus geom_col(): the key difference

Featuregeom_bar()geom_col()
Default statisticstat_countstat_identity
Bar heightNumber of rowsExisting y value
Needs a y mapping?Usually noYes
Typical useFrequency and category countsTotals, averages and other summaries
Quick memory aid: geom_bar() counts; geom_col() uses your column of values.

5. Grouped bar charts with position = "dodge"

A grouped bar chart places bars for subcategories next to each other. It is useful when you want to compare each subgroup directly within a main category.

In the following example, drv identifies drivetrain type. Mapping it to fill gives each drivetrain a colour, while position = "dodge" separates the bars.

ggplot(mpg, aes(x = class, fill = drv)) +
  geom_bar(position = "dodge") +
  labs(
    title = "Vehicle counts by class and drivetrain",
    x = "Vehicle class",
    y = "Number of vehicles",
    fill = "Drivetrain"
  ) +
  scale_fill_brewer(palette = "Dark2") +
  theme_minimal()
Grouped bar chart comparing quarterly sales for four regions
Grouped bar chart preview using the downloadable quarterly sales practice data.

Grouped bars with pre-calculated values

ggplot(sales, aes(x = region, y = sales, fill = quarter)) +
  geom_col(position = "dodge", width = 0.8) +
  labs(
    title = "Quarterly sales by region",
    x = "Region",
    y = "Sales",
    fill = "Quarter"
  ) +
  scale_fill_brewer(palette = "Set2") +
  theme_minimal()

Use position_dodge() when you need more control over spacing. For example, position_dodge(width = 0.8) controls the dodge width.

6. Stacked bar charts with position = "stack"

A stacked bar chart places subgroup segments on top of one another. It shows both the total for each main category and the contribution of each subgroup to that total.

ggplot(mpg, aes(x = class, fill = drv)) +
  geom_bar(position = "stack") +
  labs(
    title = "Vehicle class counts by drivetrain",
    x = "Vehicle class",
    y = "Number of vehicles",
    fill = "Drivetrain"
  ) +
  scale_fill_brewer(palette = "Set2") +
  theme_minimal()
Stacked bar chart showing the contribution of online, store and wholesale sales channels in each region
Stacked bar chart preview. Segment colours identify the sales channel.

Control the order of stacked segments

The order of factor levels controls the stacking and legend order. Set factor levels explicitly when the order carries meaning.

sales$quarter <- factor(
  sales$quarter,
  levels = c("Q1", "Q2", "Q3", "Q4")
)

ggplot(sales, aes(region, sales, fill = quarter)) +
  geom_col() +
  scale_fill_brewer(palette = "Set2")

7. 100% stacked and proportional bar charts

A 100% stacked bar chart converts each category's total to the same height. Each coloured segment represents a proportion of that category. This makes it easier to compare composition when the group totals are different.

ggplot(mpg, aes(x = class, fill = drv)) +
  geom_bar(position = "fill") +
  scale_y_continuous(labels = scales::percent) +
  labs(
    title = "Drivetrain composition within vehicle classes",
    x = "Vehicle class",
    y = "Percentage",
    fill = "Drivetrain"
  ) +
  scale_fill_brewer(palette = "Set2") +
  theme_minimal()
100 percent stacked bar chart comparing the proportion of three sales channels across four regions
Each bar reaches 100%. Compare the relative size of each segment rather than the total number of sales.

Calculate percentages before plotting

library(dplyr)

mix_summary <- mix |>
  group_by(region) |>
  mutate(percent = share / sum(share) * 100) |>
  ungroup()

ggplot(mix_summary, aes(region, percent, fill = channel)) +
  geom_col() +
  labs(y = "Percentage", x = "Region", fill = "Channel") +
  scale_y_continuous(limits = c(0, 100)) +
  scale_fill_brewer(palette = "Set2") +
  theme_minimal()
Interpretation: a 100% stacked chart hides differences in group totals. If total volume matters, show the totals separately or use an ordinary stacked or grouped chart.

8. Horizontal bar charts

Horizontal bars are useful when category names are long or when there are many categories. You can use coord_flip() or map the category directly to y.

# Option 1: flip the coordinates
ggplot(mpg, aes(x = class, fill = class)) +
  geom_bar(show.legend = FALSE) +
  coord_flip() +
  labs(x = "Vehicle class", y = "Number of vehicles") +
  theme_minimal()

# Option 2: map category to y
ggplot(mpg, aes(y = class, fill = class)) +
  geom_bar(show.legend = FALSE) +
  labs(x = "Number of vehicles", y = "Vehicle class") +
  theme_minimal()
Horizontal bar chart with vehicle categories ordered by their counts
Horizontal bar chart. Sorting categories often makes this format easier to read.

9. Sort and reorder bars

Bar order can change the message of a chart. Alphabetical order is sometimes appropriate, but sorting by frequency or by a summary value can make comparisons easier.

Order by frequency

library(forcats)

ggplot(mpg, aes(x = fct_infreq(class))) +
  geom_bar(fill = "#4361EE") +
  labs(x = "Vehicle class", y = "Count") +
  theme_minimal()

Order by a numerical summary

class_summary <- mpg |>
  group_by(class) |>
  summarise(mean_hwy = mean(hwy), .groups = "drop")

ggplot(class_summary,
       aes(x = reorder(class, mean_hwy), y = mean_hwy, fill = class)) +
  geom_col(show.legend = FALSE) +
  coord_flip() +
  labs(x = "Vehicle class", y = "Mean highway MPG") +
  theme_minimal()

Set a custom category order

sales$quarter <- factor(
  sales$quarter,
  levels = c("Q1", "Q2", "Q3", "Q4")
)

10. Add values, counts and percentage labels

Labels help readers see exact values without estimating bar heights. Keep labels short and make sure they do not overlap.

Label counts from geom_bar()

ggplot(mpg, aes(class)) +
  geom_bar(fill = "#4361EE") +
  geom_text(
    stat = "count",
    aes(label = after_stat(count)),
    vjust = -0.35
  ) +
  labs(x = "Vehicle class", y = "Count") +
  theme_minimal()

Label pre-calculated values from geom_col()

ggplot(counts, aes(category, count, fill = category)) +
  geom_col(show.legend = FALSE) +
  geom_text(aes(label = count), vjust = -0.35) +
  labs(x = "Category", y = "Count") +
  theme_minimal()
Colourful bar chart with exact numerical labels above each bar
Value labels make exact comparisons easier. Use geom_text() with the correct label variable.

Place labels inside bars

ggplot(sales, aes(region, sales, fill = quarter)) +
  geom_col() +
  geom_text(
    aes(label = sales),
    position = position_stack(vjust = 0.5),
    size = 3
  ) +
  theme_minimal()

For small segments, labels may not fit. Consider removing labels from tiny segments or using a legend and a separate table.

11. Colours, palettes and themes

Use colour consistently. A fixed fill outside aes() gives all bars the same colour. Mapping fill to a variable creates a colour scale and usually a legend.

# One fixed colour
ggplot(mpg, aes(class)) +
  geom_bar(fill = "#4361EE")

# A different colour for each category
ggplot(mpg, aes(class, fill = class)) +
  geom_bar() +
  scale_fill_brewer(palette = "Set2") +
  theme_minimal() +
  theme(legend.position = "none")

# Manually select colours for groups
ggplot(mpg, aes(class, fill = drv)) +
  geom_bar() +
  scale_fill_manual(values = c(
    "4" = "#4361EE",
    "f" = "#F72585",
    "r" = "#2A9D8F"
  ))

Useful palettes include Set2, Dark2 and Paired from RColorBrewer. Choose colours with enough contrast and avoid relying on colour alone to communicate an important distinction.

12. Add error bars to summary bar charts

When a bar represents a mean or another estimate, an error bar can show uncertainty or variation. The interval must be calculated from the underlying observations; do not add arbitrary error bars.

library(dplyr)

summary_data <- mpg |>
  group_by(class) |>
  summarise(
    mean_hwy = mean(hwy, na.rm = TRUE),
    sd_hwy = sd(hwy, na.rm = TRUE),
    n = sum(!is.na(hwy)),
    se = sd_hwy / sqrt(n),
    .groups = "drop"
  )

ggplot(summary_data, aes(class, mean_hwy, fill = class)) +
  geom_col(show.legend = FALSE, width = 0.7) +
  geom_errorbar(
    aes(ymin = mean_hwy - se, ymax = mean_hwy + se),
    width = 0.18
  ) +
  labs(x = "Vehicle class", y = "Mean highway MPG ± SE") +
  theme_minimal()
Bar chart with error bars illustrating mean values and standard errors
Illustration of the appearance of error bars. In your analysis, calculate intervals from the actual data and explain whether they represent standard errors, standard deviations or confidence intervals.

13. Faceted bar charts

Facets create a separate panel for each level of another variable. They are useful when a single chart would become crowded.

ggplot(mpg, aes(class, fill = drv)) +
  geom_bar() +
  facet_wrap(~ drv) +
  scale_fill_brewer(palette = "Set2") +
  labs(x = "Vehicle class", y = "Count") +
  theme_minimal() +
  theme(legend.position = "none")

Use facet_wrap() for a sequence of panels or facet_grid() when you want a row-and-column layout.

14. Download the practice datasets

Use these small CSV files to practise geom_col(), grouped bars, stacked bars and percentage charts in R. They contain fictional demonstration values.

counts <- read.csv("category_counts.csv")
sales <- read.csv("quarterly_sales.csv")
mix <- read.csv("sales_mix.csv")

# Inspect the files
head(counts)
head(sales)
head(mix)

15. Interactive bar chart examples

The following charts are drawn in JavaScript directly in your browser. Change the chart style to see how the same example data can be displayed in different ways. These are visual learning aids; use the R code above to create ggplot2 charts in R.

Vehicle category counts

Example counts for six categories.

Quarterly sales by region

Compare four quarters side by side.

Sales channel composition

Each region contains three stacked segments.

16. Common bar chart mistakes and how to fix them

  • Using geom_bar() with a pre-calculated y value: use geom_col(), or explicitly use geom_bar(stat = "identity"). geom_col() is usually clearer.
  • Using geom_col() without y: provide a numeric y variable containing the bar heights.
  • Bars are stacked but you wanted side by side: set position = "dodge".
  • Bars are grouped but you wanted totals: use the default position = "stack".
  • Percentages do not add to 100%: check the grouping variable and denominator. position = "fill" calculates proportions within each x category.
  • Bars appear in an unexpected order: inspect factor levels with levels() and set them explicitly.
  • Text labels overlap: use horizontal bars, reduce label size, or label only important values.
  • Colours are not as expected: distinguish a fixed fill outside aes() from a mapped fill inside aes().
  • Missing values are removed: inspect missing values before plotting and decide how they should be handled.

17. Practice exercises

  1. Use mpg to create a simple bar chart showing the number of vehicles in each class.
  2. Colour the bars by vehicle class using scale_fill_brewer().
  3. Create a grouped bar chart showing vehicle counts by class and drivetrain.
  4. Convert the grouped chart into a stacked bar chart and explain what changes.
  5. Create a 100% stacked chart and compare drivetrain proportions across vehicle classes.
  6. Use quarterly_sales.csv to create grouped and stacked quarterly sales charts.
  7. Sort the vehicle classes by frequency and display the result as a horizontal bar chart.
  8. Calculate mean highway fuel economy by vehicle class and plot the summary with geom_col().
  9. Add value labels to a summary chart and make sure they do not overlap.
  10. Calculate standard errors from the raw data and add error bars to a mean chart.
Suggested learning sequence: start with geom_bar(), then learn geom_col(), grouped and stacked positions, proportions, reordering and labels. Try changing one argument at a time so you can see its effect.

Next step: Continue to the next ggplot2 lesson using the navigation at the bottom of this page, or return to the ggplot2 tutorial overview.

ggplot2 FAQ

How do I create a bar chart in ggplot2?

Use ggplot(data, aes(x = category)) + geom_bar() to count observations in each category. The default statistic is stat_count.

What is the difference between geom_bar() and geom_col()?

geom_bar() counts rows by default. geom_col() displays y values that have already been calculated or supplied in your data.

How do I create a grouped bar chart in ggplot2?

Map a grouping variable to fill and use position = "dodge", for example geom_bar(position = "dodge").

How do I create a stacked bar chart?

Map the subgroup to fill and use geom_bar() or geom_col(). The default position is "stack".

How do I make a 100 percent stacked bar chart?

Use position = "fill". Each bar is scaled to the same height, allowing you to compare proportions rather than totals.

How do I add labels to bars in ggplot2?

Add geom_text(stat = "count", aes(label = after_stat(count)), vjust = -0.3) for counts, or geom_text(aes(label = value), vjust = -0.3) for pre-calculated values.

How do I change the order of bars?

Set the category factor levels in the order you want, or use forcats::fct_reorder() and forcats::fct_infreq().

Can I make horizontal bar charts in ggplot2?

Yes. Add coord_flip() to a bar chart, or map the category to y and the value to x.