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 Basics: A Step-by-Step Guide for Beginners

Updated

Start learning ggplot2 from the beginning. This beginner-friendly lesson explains how a chart is built, how to connect columns to visual features, and how to add points, lines, labels and styling one step at a time.

This page is the beginner lesson in our complete ggplot2 tutorial. You do not need to know every ggplot2 function before starting. Work through the steps in order, run each R example, and notice how a chart changes as you add one instruction at a time.

What You Will Learn in This ggplot2 Basics Tutorial

By the end of this lesson, you should be able to create a basic chart in R and understand the code that produces it. You will learn how to:

  • Load ggplot2 and use its built-in example data.
  • Start a plot with ggplot().
  • Connect data columns to chart positions with aes().
  • Choose a geom such as points, bars or lines.
  • Add several layers using the + operator.
  • Change the chart title, axis labels and appearance.
  • Save a plot in an R object and reuse it.

What Is ggplot2?

ggplot2 is a package for making charts in R. You can use it to explore data, compare groups, find patterns and explain results. For example, you might use a scatter plot to study the relationship between two numerical variables, or a bar chart to compare several categories.

The main idea is simple: tell ggplot2 which data to use, which columns to display, and what kind of marks to draw. You can then add more instructions to improve the chart.

Think of making a chart as building with blocks

A chart is not created by one complicated command. It is assembled from smaller parts. First choose the data, then connect variables to visual positions, and finally choose how to display the observations.

Beginner tip: Do not try to memorize every ggplot2 function. Learn the basic pattern first. The same pattern is used for many different chart types.

Step 1: Prepare R and Load ggplot2

You can run the examples in RStudio or another R environment. First install ggplot2. You normally do this only once on your computer.

Install ggplot2

install.packages("ggplot2")

Load ggplot2

Whenever you start a new R session, load the package before using its functions.

library(ggplot2)

If R displays an error saying that it cannot find ggplot(), check that you have run library(ggplot2) in the current session.

Step 2: Understand the Data Before Making a Chart

We will use a dataset called mpg. It comes with ggplot2, so there is no need to download a file. The data describe fuel economy and other information for 234 vehicles.

Look at the first rows

# Display the first six rows
head(mpg)

Check the columns and their data types

# Show the structure of the dataset
str(mpg)

# Show summary information
summary(mpg)

# List the column names
names(mpg)

Important columns used in this lesson

ColumnMeaningHow we will use it
displEngine displacement in litresHorizontal position (x)
hwyHighway fuel economy in miles per gallonVertical position (y)
classVehicle category, such as compact or SUVColour or grouping
drvDrivetrain categoryColour or grouping
cylNumber of engine cylindersColour or point size

For the first chart, we will use displ and hwy. Both are numerical columns, so they are suitable for a scatter plot.

Step 3: Learn the Basic Structure of a ggplot

Most ggplot2 charts follow this pattern:

ggplot(data = YOUR_DATA, mapping = aes(x = YOUR_X, y = YOUR_Y)) +
  geom_something()

There are three important parts:

  1. ggplot(): starts the chart and identifies the dataset.
  2. aes(): connects columns in the dataset to visual properties such as x and y positions.
  3. geom_...(): tells ggplot2 what to draw, such as points, bars or lines.

Here is the same pattern using our vehicle data:

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

You may also see a shorter version. It does exactly the same thing:

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

Once you understand the longer version, the shorter version is easy to read. Many R users prefer it because it keeps the code compact.

Step 4: Create Your First ggplot2 Plot

Let's create a scatter plot. A scatter plot places one dot for each row in the dataset. The horizontal position comes from engine displacement, and the vertical position comes from highway fuel economy.

Run this code

library(ggplot2)

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

Read the code from left to right:

  • mpg is the dataset.
  • x = displ puts engine displacement on the horizontal axis.
  • y = hwy puts highway fuel economy on the vertical axis.
  • geom_point() draws the dots.

Explore a simple scatter plot

Example 1: A scatter plotInteractive visual demonstration

Each dot represents one vehicle. The example shows a general downward pattern: vehicles with larger engines often have lower highway fuel economy. The chart is a teaching illustration; run the R code above for the exact mpg data plot.

What should you notice? Each dot represents an observation. The chart helps you see the overall relationship without reading every row in the dataset.

Step 5: Understand aes() — Connecting Data to Visual Features

The function aes() is short for aesthetic mappings. In simple words, it tells ggplot2 which data column controls a visual feature.

For example, aes(x = displ, y = hwy) means:

  • Use the values in displ to decide where each point appears horizontally.
  • Use the values in hwy to decide where each point appears vertically.

Other visual features you can map

MappingWhat it changesExample
xHorizontal positionaes(x = displ)
yVertical positionaes(y = hwy)
colourColour of points or linesaes(colour = class)
fillInside colour of filled shapesaes(fill = class)
sizeSize of pointsaes(size = cyl)
shapeShape of pointsaes(shape = factor(cyl))

Colour points according to vehicle class

We can add colour = class inside aes(). Now the vehicle category decides the colour of each point.

ggplot(mpg, aes(x = displ, y = hwy,
                colour = class)) +
  geom_point()
Example 2: Colour represents a categoryDifferent colours = different classes

Colour makes it easier to see how observations from different vehicle categories are distributed. In ggplot2, the legend is created automatically for a mapped categorical variable.

Change point size using another column

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

In this example, cty controls point size. Larger values are represented by larger points. Use multiple mappings carefully: too many colours, shapes and sizes can make a chart difficult to understand.

Step 6: Mapping a Variable Is Different from Setting a Fixed Value

This is one of the most common beginner questions. Remember this simple rule:

  • Put a variable inside aes() when the data should control the appearance.
  • Put a fixed value outside aes() when you want every mark to look the same.

Mapping: colour changes according to the data

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

Setting: all points use one colour

ggplot(mpg, aes(displ, hwy)) +
  geom_point(colour = "tomato")
Example 3: Mapping versus settingCompare the two approaches

Mapped colour: categories differ

Fixed colour: one colour for all points

Notice that colour = "tomato" is outside aes(). It is a setting, not a data mapping. If you put the text "tomato" inside aes(), ggplot2 treats it as a mapped value and may create a legend.

Step 7: Choose What You Want ggplot2 to Draw

A geom is the type of mark used in a chart. You have already used geom_point() to draw dots. Different questions need different geoms.

Some useful geoms for beginners

FunctionWhat it drawsWhen to use it
geom_point()Points or dotsExplore the relationship between two numerical variables
geom_bar()Bars showing countsCount observations in categories
geom_col()Bars using supplied valuesDisplay values already calculated in a data frame
geom_line()Connected lineShow a sequence or trend, often over time
geom_histogram()Distribution barsUnderstand the distribution of a numerical variable
geom_boxplot()Box and whiskersCompare distributions across groups

Example: A bar chart

To count how many vehicles belong to each class, use geom_bar().

ggplot(mpg, aes(x = class)) +
  geom_bar(fill = "cornflowerblue")
Example 4: A colourful bar chartCategory counts

A bar chart compares categories. The example is illustrative; the R code above calculates the actual counts from the mpg dataset.

Example: A line chart

Use geom_line() when the order of observations matters, such as a monthly sales trend or yearly change.

sales <- data.frame(
  month = 1:6,
  revenue = c(12, 15, 13, 19, 22, 26)
)

ggplot(sales, aes(x = month, y = revenue)) +
  geom_line(colour = "royalblue", linewidth = 1.2) +
  geom_point(colour = "tomato", size = 3)
Example 5: A line chartIllustrative monthly revenue

The line connects observations in month order. In a real project, replace the example values with your own data.

Step 8: Add Layers One at a Time

A layer adds something to the chart. You can begin with points, then add a trend line, and finally add labels. This is easier to understand than writing a long plotting command all at once.

Start with points

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

Add a fitted trend line

ggplot(mpg, aes(displ, hwy)) +
  geom_point(alpha = 0.6) +
  geom_smooth(method = "lm", se = FALSE)

geom_smooth() adds a fitted trend. The option method = "lm" asks ggplot2 to use a linear model. The option se = FALSE hides the shaded confidence band.

Add colour and transparency

ggplot(mpg, aes(displ, hwy, colour = class)) +
  geom_point(alpha = 0.65, size = 2.5) +
  geom_smooth(aes(group = 1), method = "lm",
              se = FALSE, colour = "black")

Here, alpha controls transparency and size controls point size. The trend line is black for all groups because its colour is set outside aes().

Example 6: A plot built from layersPoints + trend line + labels

A finished plot can combine individual observations, a summary line and explanatory labels. Each component is added as a separate layer or plot setting.

Important: use the plus sign to add ggplot2 layers. It is not the same as the pipe operator (|>) used to pass data between R functions.

Step 9: Add a Title, Axis Labels and a Theme

A chart should explain itself. A reader should be able to understand what is being measured without guessing. Use labs() to add a title and clear axis labels.

ggplot(mpg, aes(displ, hwy)) +
  geom_point(colour = "steelblue") +
  labs(
    title = "Engine size and fuel economy",
    subtitle = "Each point represents one vehicle",
    x = "Engine displacement (litres)",
    y = "Highway fuel economy (miles per gallon)",
    caption = "Source: ggplot2 mpg dataset"
  ) +
  theme_minimal()

What does theme_minimal() do?

A theme controls the non-data appearance of a chart, such as its background, grid lines, text and legend position. theme_minimal() gives a clean appearance with a simple background.

You can try other built-in themes too:

p <- ggplot(mpg, aes(displ, hwy)) +
  geom_point()

p + theme_gray()
p + theme_bw()
p + theme_classic()
p + theme_minimal()
p + theme_light()

Step 10: Store and Reuse a ggplot Object

A plot created with ggplot2 is an R object. This means you can save it in a variable and display it later. You can also add more layers to the saved object.

Save a basic plot

p <- ggplot(mpg, aes(displ, hwy)) +
  geom_point()

# Display the plot
p

Make another version of the same plot

# Add a minimal theme
p + theme_minimal()

# Add a title
p + labs(title = "Engine size and highway fuel economy")

# Add a trend line
p + geom_smooth(method = "lm", se = FALSE)

The original object p remains available. Each expression creates a displayed version with the extra instruction; it does not permanently change p unless you assign the result back to it.

Save a chart as an image

ggsave("my-first-ggplot.png", plot = p,
       width = 8, height = 5, dpi = 300)

For more options, see the ggplot2 save and export lesson.

The Grammar of Graphics: How the Pieces Fit Together

You may hear the phrase grammar of graphics when learning ggplot2. It simply means that a chart is described using a set of components that work together. You do not need to master every component today, but you should recognize the main ones.

PartBeginner explanationExample
DataThe table containing your observationsmpg
AestheticsWhich columns control visual featuresaes(displ, hwy)
GeomsWhat marks are drawngeom_point()
StatsCalculations made before drawing some marksgeom_smooth()
ScalesHow values are translated into colours, sizes and axesscale_colour_manual()
CoordinatesHow the plotting area is arranged or viewedcoord_flip()
FacetsHow one chart is split into several panelsfacet_wrap()
ThemeHow titles, text, grids and backgrounds looktheme_minimal()

For now, remember the beginner pattern: data + aes() + geom + optional layers. The later lessons explain scales, facets, statistics and themes in more detail.

Common ggplot2 Beginner Mistakes

1. R says it cannot find ggplot()

Why it happens: ggplot2 has not been loaded in the current R session.

library(ggplot2)

2. R says an object was not found

Why it happens: the column name may be misspelled, or it may not exist in the selected dataset.

names(mpg)
str(mpg)

3. You see a blank plot

Why it happens: you created the starting plot with ggplot() but did not add a geom. Add a layer such as geom_point() or geom_bar().

4. You get an unexpected legend

Why it happens: you may have placed a fixed colour or size inside aes(). Put fixed values outside aes().

5. You use the wrong geom for your data

Why it happens: different chart types answer different questions. Use geom_point() for relationships, geom_bar() for category counts and geom_histogram() for numerical distributions.

6. Your plot does not appear when using a script

Why it happens: a stored plot object may need to be printed explicitly inside a function or some scripts.

p <- ggplot(mpg, aes(displ, hwy)) +
  geom_point()

print(p)

Practice Exercises: Test Your ggplot2 Basics

Try these small tasks yourself. The aim is to change one part of the code at a time and observe what happens.

  1. Create a scatter plot using displ on the x-axis and cty on the y-axis.
  2. Change the point colour to "darkorange" by setting it outside aes().
  3. Map class to colour inside aes().
  4. Make a bar chart showing the number of vehicles in each class.
  5. Add a title and descriptive axis labels using labs().
  6. Save your plot in an object called my_plot, then add theme_minimal().

One possible solution

my_plot <- ggplot(mpg, aes(displ, cty,
                           colour = class)) +
  geom_point(size = 2.5, alpha = 0.7) +
  labs(
    title = "Engine size and city fuel economy",
    x = "Engine displacement (litres)",
    y = "City fuel economy (mpg)",
    colour = "Vehicle class"
  ) +
  theme_minimal()

my_plot

What Should You Learn After ggplot2 Basics?

You now know the basic structure of a ggplot2 chart. The next step is to study each part in more detail. Follow these lessons in a gradual order:

You can also return to the complete ggplot2 tutorial to see the full learning pathway.

Key idea to remember: start with your data, use aes() to connect columns to visual features, and add a geom to draw the chart. Build more complex visualizations one layer at a time.

ggplot2 FAQ

What is ggplot2 in R?

ggplot2 is an R package used to create charts and data visualizations. You build a chart by combining data, aesthetic mappings and geometric layers.

Is ggplot2 difficult for beginners?

No. Start with a data frame, choose two columns, map them with aes(), and add a geom such as geom_point(). You can learn more features gradually.

What does ggplot() do?

ggplot() creates the starting plot object. It can store the dataset and default aesthetic mappings, but you usually add a geom to display the data.

What does aes() mean in ggplot2?

aes() means aesthetic mappings. It connects data columns to visual properties such as horizontal position, vertical position, colour, size and shape.

Why do we use the plus sign in ggplot2?

The + operator adds another component or layer to a plot. For example, you can add points, a trend line, labels and a theme to the same chart.

What is the difference between geom_point() and geom_line()?

geom_point() draws a separate point for each observation. geom_line() connects observations in an order, which is useful for showing a trend or sequence.

Can I save a ggplot in a variable?

Yes. Assign the plot to an object, such as p <- ggplot(data, aes(x, y)) + geom_point(). You can print p or add more layers to it later.