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

ggplot2 Aesthetic Mappings: A Complete Guide to aes() in R

Updated

The aes() function tells ggplot2 which columns in your data should control the visible parts of a chart. Learn each mapping with colourful visual examples, clear explanations and R code you can run yourself.

This lesson is part of the ggplot2 tutorial. We will use the built-in mpg data supplied with ggplot2. The examples assume that you have installed and loaded the package.

The central idea: aes() does not usually choose one colour or one size for the whole chart. It tells ggplot2 to look at a column and use each row's value to control a visual feature. That is why a mapping can produce different-looking points and a legend.

1. What are aesthetics in ggplot2?

In a chart, an aesthetic is a visual property of a mark. A mark might be a point, bar, line, box or text label. For example, a scatter plot uses the horizontal position of a point for one variable and its vertical position for another. It may also use colour to show a category.

Think of aesthetics as the visual channels through which a chart communicates information.

AestheticWhat it changesTypical use
xHorizontal positionTime, age, engine size
yVertical positionPrice, fuel efficiency, sales
colourOutline or line colourDistinguish groups or categories
fillInterior colour of filled shapesBars, boxplots, areas
sizePoint or line sizeRepresent a numeric quantity
shapePoint symbolDistinguish a few categories
alphaTransparencyShow overlapping points or density
groupWhich observations belong togetherSeparate lines or summaries by group

Position: x and y

Each dot's position represents two numeric values.

Colour: categories

Colour helps you compare categories within the same plot.

Size: numeric values

Larger circles represent larger values.

Shape: categories

Different symbols can identify a small number of groups.

These canvas drawings are teaching illustrations created with JavaScript. They explain the visual idea; the R examples below generate plots from the actual mpg dataset.

2. How aes() works

The function aes() is short for aesthetics. You normally place it inside ggplot() or inside a layer such as geom_point().

Read this code from left to right:
ggplot(data = mpg, aes(x = displ, y = hwy)) +
  geom_point()
  1. ggplot(data = mpg, ...) tells ggplot2 to use the mpg data frame.
  2. aes(x = displ, y = hwy) maps the displ column to horizontal position and hwy to vertical position.
  3. geom_point() says to draw the observations as points.
  4. The + joins the plot definition and its layer.

Notice that we write column names without quotation marks inside aes(). We write displ, not "displ", because ggplot2 needs to evaluate the column in the supplied data.

3. Map x and y: the foundation of most charts

The x and y aesthetics control where each mark appears. In the mpg data, displ is engine displacement in litres and hwy is highway fuel economy in miles per gallon.

library(ggplot2)

ggplot(mpg, aes(x = displ, y = hwy)) +
  geom_point()

Each vehicle becomes one point. A vehicle with a larger engine is farther to the right; a vehicle with higher highway fuel economy is higher on the chart. Look for the overall pattern rather than expecting every point to follow a straight line.

How x and y locate each observation

Changing either mapping changes the position of the observations.

Use short notation when it is clear

These two forms are equivalent:

ggplot(mpg, aes(x = displ, y = hwy)) +
  geom_point()

ggplot(mpg, aes(displ, hwy)) +
  geom_point()

For learning and for longer code, naming x and y explicitly can make the mapping easier to read.

4. Map colour to a variable

Use colour when you want points or lines to have different colours according to a data variable. In the example below, each vehicle class is assigned a colour.

ggplot(mpg, aes(x = displ, y = hwy, colour = class)) +
  geom_point(size = 2.5, alpha = 0.8)

Because class is categorical, ggplot2 uses a distinct colour for each class and normally adds a legend. The legend explains which colour belongs to which class.

Colour mapped to a category

The legend is generated because colour is mapped to a variable.

Colour can also represent a number

If you map a continuous numeric variable to colour, ggplot2 uses a colour gradient rather than one colour per category.

ggplot(mpg, aes(displ, hwy, colour = cty)) +
  geom_point(size = 2.5)

Here, cty is city fuel economy. A continuous colour scale helps show how the numeric values vary.

Practical advice: use colour for a variable that matters to your question. If the colours do not help the reader compare anything, leave the mapping out.

5. Understand colour versus fill

These two aesthetics are related, but they are not interchangeable in every geom.

  • colour controls the outline of a filled shape and the colour of lines and point symbols.
  • fill controls the inside of shapes that have an interior area, such as bars, boxplots and some point shapes.
# Bars with different interior fills
ggplot(mpg, aes(x = class, fill = drv)) +
  geom_bar()

# A boxplot with a coloured outline and a filled interior
ggplot(mpg, aes(x = class, y = hwy)) +
  geom_boxplot(colour = "grey25", fill = "skyblue")

Fill changes the interior

Think of fill as the paint inside the bar.

Colour changes the outline

Think of colour as the border or stroke.

Common confusion: mapping fill in geom_point() may appear to do nothing with the default solid circle. Some point shapes support both an outline and a fill. For bars, boxplots and areas, fill is commonly the aesthetic you want.

6. Map size to a numeric variable

The size aesthetic changes the size of a point or line. It is often used to represent a numeric quantity, for example population, revenue or city fuel economy.

ggplot(mpg, aes(x = displ, y = hwy, size = cty)) +
  geom_point(alpha = 0.6)

In this example, the point size is connected to cty. A larger point represents a higher value. ggplot2 adds a size guide so readers can interpret the circles.

Point size represents a value

Use a moderate size range so points do not hide one another.

Set a useful size range

ggplot(mpg, aes(displ, hwy, size = cty)) +
  geom_point(alpha = 0.65) +
  scale_size(range = c(2, 8))

The range controls how small and large the displayed points can become. Do not make the range so wide that a few large points dominate the chart.

7. Map shape to a category

The shape aesthetic changes the symbol used for a point. It can help distinguish groups when colour alone is not enough, or when a chart may be printed in greyscale.

ggplot(mpg, aes(displ, hwy, shape = drv)) +
  geom_point(size = 3)

The drv variable identifies the drive type. In this dataset it has a small number of categories, which makes it suitable for shape mapping.

Different point symbols

Shapes are easiest to compare when there are only a few groups.

Important: shape is not ideal for a variable with many categories. Too many symbols are hard to distinguish. Use colour, facets or separate charts when there are many groups.

8. Map alpha to transparency

alpha controls transparency. A value near 1 is opaque, while a value closer to 0 is more transparent. Transparency is especially helpful when many points overlap.

# A fixed transparency for all points
ggplot(mpg, aes(displ, hwy)) +
  geom_point(alpha = 0.35)

# Transparency mapped to a variable
ggplot(mpg, aes(displ, hwy, alpha = cty)) +
  geom_point()

The first example sets one transparency level for every point. The second maps transparency to the cty column, so it varies with the data. In many beginner charts, a fixed alpha is simpler and easier to interpret.

Transparency reduces overplotting

Where points overlap, the area appears darker.

9. Map group to connect observations correctly

The group aesthetic tells ggplot2 which observations belong together when a geom draws connected elements, such as lines. It is particularly important for line charts and grouped summaries.

# Draw a separate trend line for each drive type
ggplot(mpg, aes(displ, hwy, group = drv, colour = drv)) +
  geom_smooth(method = "lm", se = FALSE)

Here, group = drv identifies separate groups, and colour = drv makes those groups visually distinguishable. The colour mapping often implies grouping for many geoms, but writing group explicitly can make your intention clear.

Why grouping matters in a line chart

ggplot(economics_long,
       aes(date, value, group = variable, colour = variable)) +
  geom_line()

The economics_long dataset is available in the ggplot2 package. Each economic variable should form its own line. Without a suitable group mapping, ggplot2 may connect observations in an unintended way.

Separate groups, separate lines

Grouping tells the line geom which observations to connect.

10. Mapping versus setting: the most important distinction

This is one of the most common sources of confusion for new ggplot2 users.

Mapping inside aes(): let the data decide the visual value.
ggplot(mpg, aes(displ, hwy, colour = class)) +
  geom_point()

Each row's class value determines the point colour. The plot usually has a legend because the colours communicate data categories.

Setting outside aes(): give every point the same fixed value.
ggplot(mpg, aes(displ, hwy)) +
  geom_point(colour = "steelblue")

Every point is steel blue. There is no category mapping, so there is normally no colour legend.

Mapped colour

Inside aes(): colour varies by data category.

Fixed colour

Outside aes(): every point uses the same colour.

What you wantCorrect code pattern
Colour changes according to a columnaes(colour = class)
All points are bluegeom_point(colour = "blue")
Bar fill changes by categoryaes(fill = drv)
All bars are orangegeom_bar(fill = "orange")
Point size changes according to a numberaes(size = cty)
All points have one sizegeom_point(size = 3)

11. Global and local aesthetic mappings

You can define mappings once in ggplot() and let layers inherit them. This is called a global mapping.

# Global mappings: both layers inherit x and y
ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE)

Here, both the points and the fitted line use displ on x and hwy on y.

You can also add a mapping to one layer only. This is a local mapping.

# Colour is mapped only for the points
ggplot(mpg, aes(displ, hwy)) +
  geom_point(aes(colour = class)) +
  geom_smooth(method = "lm", se = FALSE,
              colour = "black")

The points are coloured by vehicle class, while the smooth line is fixed black. This works because the point layer has its own mapping and the line layer has a fixed colour setting.

When should you use inherit.aes = FALSE?

By default, a layer inherits the main plot's mappings. Use inherit.aes = FALSE when a layer has its own data and should not use those inherited mappings.

ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  geom_text(
    data = data.frame(
      x = 6, y = 40, label = "Example label"
    ),
    aes(x = x, y = y, label = label),
    inherit.aes = FALSE
  )

The text layer uses a separate small data frame with columns named x, y and label. It does not need the displ and hwy columns from mpg.

12. Combine several aesthetics in one chart

You can map more than one variable in a single plot. For example, map engine size to x, highway economy to y, vehicle class to colour and city economy to size.

ggplot(mpg,
       aes(x = displ,
           y = hwy,
           colour = class,
           size = cty)) +
  geom_point(alpha = 0.7)

This chart can communicate four dimensions: x position, y position, colour and size. However, every extra mapping adds work for the reader. Use multiple aesthetics only when each one contributes useful information.

Several visual channels together

Position, colour and size can work together, but avoid visual clutter.

Make the chart easier to read

ggplot(mpg,
       aes(displ, hwy,
           colour = class,
           size = cty)) +
  geom_point(alpha = 0.65) +
  labs(
    x = "Engine displacement (litres)",
    y = "Highway miles per gallon",
    colour = "Vehicle class",
    size = "City MPG",
    title = "Engine size and fuel economy"
  )

13. Legends, labels and scales

When an aesthetic is mapped to a variable, ggplot2 uses a scale to translate data values into visual values. For a categorical colour mapping, the scale assigns colours to categories. For a numeric size mapping, it translates numbers into point sizes.

You can change the scale when the default is not suitable.

# Choose specific colours for categories
ggplot(mpg, aes(displ, hwy, colour = drv)) +
  geom_point(size = 2.5) +
  scale_colour_manual(
    values = c(
      "4" = "#2563eb",
      "f" = "#16a34a",
      "r" = "#ea580c"
    )
  )

You can also improve legend and axis wording with labs():

ggplot(mpg, aes(displ, hwy, colour = class)) +
  geom_point() +
  labs(
    x = "Engine size (litres)",
    y = "Highway fuel economy (mpg)",
    colour = "Vehicle category",
    title = "Engine size and highway economy"
  )
Remember: aes() creates the mapping. Functions such as scale_colour_manual(), scale_size() and labs() help control how that mapping is displayed.

14. Aesthetic availability depends on the geom

Not every geom uses every aesthetic. A point has a position and may have colour, fill, size, shape and alpha. A bar has position, fill, colour and possibly alpha. A line uses position, colour, linewidth and alpha, but it does not have a filled interior in the same way as a bar.

GeomCommon useful aestheticsExample
geom_point()x, y, colour, fill (some shapes), size, shape, alphaScatter plot
geom_line()x, y, colour, linewidth, linetype, alpha, groupTime series
geom_bar()x, fill, colour, alphaCategory counts
geom_col()x, y, fill, colour, alphaPre-calculated values
geom_boxplot()x, y, fill, colour, alpha, groupDistribution by category
geom_area()x, y, fill, colour, alpha, groupArea over time

For example, use geom_bar() when you want ggplot2 to count observations, and geom_col() when your data already contains the heights you want to display.

# Count cars in each class; ggplot2 calculates the count
ggplot(mpg, aes(x = class, fill = class)) +
  geom_bar()

# Use values that have already been calculated
class_summary <- data.frame(
  class = c("compact", "midsize", "suv"),
  total = c(47, 41, 62)
)

ggplot(class_summary, aes(class, total, fill = class)) +
  geom_col()

15. A practical step-by-step workflow

When you create a new ggplot2 chart, follow this sequence. It reduces mistakes and helps you decide which mappings are genuinely useful.

  1. Choose the data. Identify the data frame and inspect it with head(), str() and names().
  2. Choose the question. Decide what you want the reader to compare or understand.
  3. Choose x and y. Put the main explanatory variable on x and the outcome or value of interest on y, where appropriate.
  4. Choose a geom. Use points for relationships, lines for ordered trends, bars for counts or pre-calculated values, and boxplots for distributions.
  5. Add one extra mapping if it helps. Consider colour, fill, size or shape to distinguish a meaningful group or quantity.
  6. Check the legend. Make sure it explains the mapping and is not redundant.
  7. Improve labels. Use labs() to give axes and legends meaningful names.
  8. Review the result. Check for overlap, confusing colours, missing values and unnecessary complexity.
# A complete example using the workflow
ggplot(mpg,
       aes(x = displ,
           y = hwy,
           colour = drv)) +
  geom_point(size = 2.5, alpha = 0.75) +
  labs(
    title = "Engine displacement and highway fuel economy",
    x = "Engine displacement (litres)",
    y = "Highway fuel economy (mpg)",
    colour = "Drive type"
  ) +
  theme_minimal()

16. Common mistakes and how to fix them

1. Putting a fixed colour inside aes()

# Incorrect for a single fixed colour
ggplot(mpg, aes(displ, hwy, colour = "blue")) +
  geom_point()

# Correct: fixed colour outside aes()
ggplot(mpg, aes(displ, hwy)) +
  geom_point(colour = "blue")

In the first version, "blue" is treated as a constant category label, not as a request to use the literal blue colour. ggplot2 may create a legend for that one category.

2. Using a column name that does not exist

Check column names with names(mpg). R is case-sensitive: displ and Displ are different names.

3. Mapping too many variables

Colour, size, shape and alpha all at once may overload a chart. Start with x and y, then add only the visual channels needed to answer the question.

4. Using shape for too many categories

Most readers can distinguish only a limited number of point symbols. For many groups, consider colour or facets instead.

5. Expecting fill to colour every point

Many point shapes use colour rather than fill. Try a filled point shape such as shape 21 if you need both an outline and an interior fill.

ggplot(mpg, aes(displ, hwy, fill = drv)) +
  geom_point(shape = 21, colour = "grey20", size = 3)

6. Forgetting how layers inherit mappings

A layer normally inherits global mappings. If its data frame does not contain the required columns, you may see an error such as “object not found”. Add a suitable local mapping or use inherit.aes = FALSE when the layer is independent.

17. Practice exercises

Try these tasks with the mpg dataset. First attempt each one yourself, then compare your code with the suggested answer.

  1. Create a scatter plot with displ on x and hwy on y.
  2. Map class to colour and add points with size 2.
  3. Map drv to shape. Keep the point size fixed at 3.
  4. Map cty to size and set all points to 50% transparency.
  5. Create a bar chart of vehicle counts by class, using drv as the fill mapping.
  6. Create two plots: one with colour mapped to class, and one with all points fixed to purple. Explain why only one needs a category legend.
  7. Make a plot with global x and y mappings, colour the points locally by drv, and add a black linear trend line.
Show suggested solutions
# 1. x and y
ggplot(mpg, aes(displ, hwy)) +
  geom_point()

# 2. Colour mapped to class
ggplot(mpg, aes(displ, hwy, colour = class)) +
  geom_point(size = 2)

# 3. Shape mapped to drive type
ggplot(mpg, aes(displ, hwy, shape = drv)) +
  geom_point(size = 3)

# 4. Size mapped to city MPG; fixed alpha
ggplot(mpg, aes(displ, hwy, size = cty)) +
  geom_point(alpha = 0.5)

# 5. Counts by class, filled by drive type
ggplot(mpg, aes(class, fill = drv)) +
  geom_bar()

# 6. Mapped versus fixed colour
ggplot(mpg, aes(displ, hwy, colour = class)) +
  geom_point()

ggplot(mpg, aes(displ, hwy)) +
  geom_point(colour = "purple")

# 7. Local mapping for points, fixed line colour
ggplot(mpg, aes(displ, hwy)) +
  geom_point(aes(colour = drv)) +
  geom_smooth(method = "lm", se = FALSE,
              colour = "black")

18. What to learn next

Now that you understand aesthetic mappings, continue with the lessons on geoms and layers, scales, labels and themes. These topics build on aes(): geoms decide what marks to draw, scales control how mapped values appear, and themes control the non-data appearance of the chart.

Key takeaway: Put data-driven mappings inside aes(); put fixed visual settings outside it. Begin with x and y, add colour or fill when categories matter, and use size, shape, alpha and group only when they improve the explanation.

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

ggplot2 FAQ

What does aes() do in ggplot2?

aes() maps variables in a data frame to visual properties of a plot, such as x position, y position, colour, fill, size, shape, alpha and group.

What is the difference between mapping and setting an aesthetic?

A mapping inside aes() connects a visual property to a data variable. A setting outside aes() gives every relevant mark a fixed value.

What is the difference between colour and fill in ggplot2?

colour controls outlines and line colours, while fill controls the interior of filled shapes such as bars, boxes and polygons.

Can I use more than one aesthetic in aes()?

Yes. You can map several variables at once, but too many visual encodings can make a chart confusing. Choose mappings that help answer your question.

Why does ggplot2 show a legend?

A legend is usually created when an aesthetic is mapped to a variable inside aes(). A fixed aesthetic set outside aes() normally does not need a legend.

What does inherit.aes = FALSE mean?

It tells a layer not to inherit the aesthetic mappings defined in the main ggplot() call. This is useful when a layer uses different data or different x and y variables.