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 Tutorial: A Complete Guide to Data Visualization in R

Updated

Learn how to create, customize and interpret data visualizations in R with ggplot2. This step-by-step guide covers the grammar of graphics, aesthetic mappings, chart types, statistical layers, scales, facets, themes and exporting publication-ready plots using practical examples.

What Is ggplot2 in R?

ggplot2 is a widely used R package for creating statistical graphics and data visualizations. It is based on the grammar of graphics, a structured way of describing a chart through data, aesthetic mappings, geometric objects, statistical transformations, scales, coordinate systems and themes. Rather than choosing a fixed chart template, you construct a visualization by combining these components.

With ggplot2, you can create scatter plots, bar charts, histograms, line graphs, boxplots, density plots, violin plots, area charts and many other graphics. A simple plot can be extended with colour scales, labels, regression lines, facets, annotations and custom themes. This makes ggplot2 useful for exploratory data analysis, academic research, business analytics, statistical reporting and communicating findings.

ggplot2 is part of the tidyverse ecosystem. It works naturally with data frames and data preparation tools such as dplyr. A common R workflow is to clean, filter and summarize data with dplyr, then visualize the prepared data with ggplot2.

What can you create with ggplot2?

  • Relationships: scatter plots and fitted trend lines for exploring associations between numerical variables.
  • Comparisons: bar charts, boxplots and violin plots for comparing categories or groups.
  • Distributions: histograms and density plots for understanding spread, skewness and unusual values.
  • Trends: line charts for displaying ordered or time-based observations.
  • Subgroup analysis: facets for displaying related charts in separate panels.
  • Presentation graphics: themes, labels, scales and annotations for reports and publications.

Why Use ggplot2 for Data Visualization?

Base R includes plotting functions, but ggplot2 provides a consistent grammar for constructing and extending charts. Once you understand the relationship between data, aesthetics and geoms, the same approach can be reused across many visualization tasks.

Advantages of ggplot2

  • Consistent syntax: most charts begin with ggplot(data, aes(...)) and add layers with +.
  • Layer-based construction: combine points, lines, summaries, labels and reference marks.
  • Scales and legends: mapped variables generally produce suitable scales and legends automatically.
  • Faceting: compare subgroups in panels without writing a separate plotting command for each group.
  • Reproducibility: plots are defined in code and can be regenerated when data change.
  • R ecosystem integration: works with data frames, factors, statistical summaries and tidyverse workflows.

How to Install and Load ggplot2 in R

Install ggplot2 from CRAN. Installation is normally required once for each R library, while loading the package is required in every new R session.

Install the package

install.packages("ggplot2")

Load ggplot2 and check the version

library(ggplot2)

packageVersion("ggplot2")
?ggplot

Optional: install the tidyverse collection

If you also need dplyr, tidyr, readr and other tidyverse packages, you can install the complete collection. You do not need to install the full tidyverse just to use ggplot2.

install.packages("tidyverse")
library(tidyverse)

Remember: do not run install.packages() every time you make a chart. Install once, then load ggplot2 with library(ggplot2) in each new session.

The mpg Dataset: Data Used in This ggplot2 Tutorial

Most examples in this tutorial use mpg, a dataset included with ggplot2. It contains 234 observations of cars from several manufacturers, including information about engine displacement, drivetrain, vehicle class, city fuel economy and highway fuel economy. No external CSV file is required.

Inspect the dataset

library(ggplot2)

head(mpg)
str(mpg)
summary(mpg)
names(mpg)

Important mpg variables

VariableDescriptionVisualization use
manufacturerVehicle manufacturerCompare or group manufacturers
modelVehicle modelIdentify individual observations
displEngine displacement in litresNumerical axis or explanatory variable
yearModel year (1999 or 2008)Compare model-year groups
cylNumber of cylindersColour, shape or grouping variable
transTransmission typeCompare transmission categories
drvDrivetrain: front, rear or four-wheel driveColour mapping or facets
ctyCity fuel economy (mpg)Distribution or comparison
hwyHighway fuel economy (mpg)Outcome variable in examples
flFuel typeGroup or filter observations
classVehicle categoryBar charts, boxplots and facets

Check data types and categories

str(mpg)
table(mpg$class)
unique(mpg$drv)

Numerical variables are often mapped to continuous axes. Categorical variables are commonly mapped to colour, fill, shape or facets. Inspect the data before choosing the mappings.

Create Your First ggplot2 Chart

Suppose you want to examine whether cars with larger engines tend to have lower highway fuel economy. Map engine displacement (displ) to the x-axis and highway miles per gallon (hwy) to the y-axis.

Basic scatter plot with ggplot() and geom_point()

library(ggplot2)

ggplot(data = mpg, aes(x = displ, y = hwy)) +
  geom_point()
ggplot2 scatter plot of engine displacement in litres against highway fuel economy in miles per gallon, with points coloured by vehicle class and a linear trend line
Scatter plot made from the mpg dataset. Each point represents one vehicle observation. Download scatter plot image.

The expression contains two essential components:

  • ggplot(data = mpg, aes(x = displ, y = hwy)) supplies the dataset and maps two variables to horizontal and vertical positions.
  • geom_point() adds a point for each observation.

The + operator adds a layer to a ggplot object. It is not the same as the pipe operator used in data manipulation.

Add colour and a fitted trend line

ggplot(mpg, aes(displ, hwy, colour = class)) +
  geom_point(alpha = 0.8) +
  geom_smooth(aes(group = 1), method = "lm",
              se = FALSE, colour = "black") +
  labs(
    title = "Engine displacement and highway fuel economy",
    x = "Engine displacement (litres)",
    y = "Highway fuel economy (mpg)",
    colour = "Vehicle class"
  ) +
  theme_minimal()

This version maps vehicle class to colour and adds a linear trend line. The colour mapping is inside aes(); the fixed black line colour is outside it.

The Grammar of Graphics Explained

The grammar of graphics is the conceptual foundation of ggplot2. It describes a graphic through components that specify the data, visual mappings and marks used to represent observations. Understanding these components helps you build charts deliberately rather than memorizing unrelated commands.

The main components of a ggplot

ComponentPurposeExamples
DataData frame containing observationsmpg, diamonds
AestheticsMap variables to visual propertiesaes(x, y, colour, fill)
GeometriesChoose visual marksgeom_point(), geom_col()
StatisticsCalculate summaries or transformationsstat_count(), stat_smooth()
ScalesTranslate data values into visual valuesscale_colour_manual()
CoordinatesControl the coordinate system and viewing windowcoord_cartesian(), coord_flip()
FacetsSplit observations into panelsfacet_wrap(), facet_grid()
ThemesStyle text, backgrounds, grids and legendstheme_minimal(), theme()

Combine components in one chart

ggplot(mpg, aes(displ, hwy)) +
  geom_point(aes(colour = factor(cyl)), alpha = 0.7) +
  geom_smooth(method = "lm", se = FALSE,
              colour = "black") +
  labs(
    title = "Engine displacement and fuel economy",
    x = "Engine displacement (litres)",
    y = "Highway fuel economy (mpg)",
    colour = "Cylinders"
  ) +
  theme_minimal()

Each line adds an instruction to the same plot. ggplot2 supplies defaults for many components, so you do not have to specify every detail.

Aesthetic Mappings with aes() in ggplot2

The aes() function maps data variables to visual properties called aesthetics. Common aesthetics include x-position, y-position, colour, fill, size, shape, alpha and group.

Common aesthetic mappings

AestheticVisual effectExample
xHorizontal positionaes(x = displ)
yVertical positionaes(y = hwy)
colourPoint outline or line colouraes(colour = class)
fillInterior fill colouraes(fill = drv)
sizePoint size or line widthaes(size = cty)
shapePoint symbolaes(shape = factor(cyl))
alphaTransparencyaes(alpha = cty)
groupDefines observations connected or summarized togetheraes(group = drv)

Map multiple variables at the same time

ggplot(mpg, aes(
  x = displ,
  y = hwy,
  colour = factor(cyl),
  size = cty
)) +
  geom_point(alpha = 0.7) +
  labs(colour = "Cylinders", size = "City mpg") +
  theme_minimal()
ggplot2 scatter plot demonstrating multiple aesthetic mappings: engine displacement on the x-axis, highway fuel economy on the y-axis, point colour for cylinder count and point size for city fuel economy
Multiple aesthetic mappings communicate several variables in one graphic. Download aesthetic mapping image.

Mapping a variable versus setting a fixed value

Map a variable inside aes()

# Colour varies according to vehicle class
ggplot(mpg, aes(displ, hwy, colour = class)) +
  geom_point()

Set a fixed colour outside aes()

# All points use the same colour
ggplot(mpg, aes(displ, hwy)) +
  geom_point(colour = "steelblue")

If a fixed colour is placed inside aes(), ggplot2 interprets it as a mapped value rather than a fixed setting. This can create an unexpected legend.

Build Plots with Layers

A layer can contain a geom, a statistical transformation, position adjustments, aesthetic mappings and other settings. The usual pattern is to create a base plot and add layers with +.

Create and store a base plot

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

Add points, a regression line and labels

p +
  geom_point(alpha = 0.6) +
  geom_smooth(method = "lm", se = TRUE) +
  labs(
    title = "Engine size and highway fuel economy",
    x = "Engine displacement (litres)",
    y = "Highway fuel economy (mpg)"
  ) +
  theme_minimal()

Layer-specific data and mappings

A layer can inherit the plot's data and mappings or define its own. This is useful when adding a summary or reference mark based on a different data object.

ggplot(mpg, aes(displ, hwy)) +
  geom_point(alpha = 0.5) +
  geom_smooth(
    data = mpg,
    aes(x = displ, y = hwy),
    method = "lm",
    se = FALSE,
    colour = "red",
    inherit.aes = FALSE
  )

Geoms and Common ggplot2 Chart Types

Geoms determine the marks used to represent data. Choose a geom according to the analytical question and the types of variables being examined.

Common ggplot2 geoms

GeomTypical purposeExample
geom_point()Relationship between numerical variablesDisplacement vs highway mpg
geom_bar()Count observations in categoriesVehicles by class
geom_col()Display supplied numerical valuesMean mpg by class
geom_histogram()Show a numerical distributionHighway mpg distribution
geom_line()Connect ordered observationsTrend across time points
geom_boxplot()Compare medians, quartiles and potential outliersFuel economy by class
geom_density()Estimate a smooth distributionFuel economy by drivetrain
geom_violin()Compare distribution shapesFuel economy by class
geom_smooth()Add a fitted trend or smootherRegression or LOESS curve
geom_text()Label observationsSelected points or categories

Bar charts: geom_bar() versus geom_col()

Use geom_bar() when ggplot2 should count observations in each category. Use geom_col() when the data already contain the numerical values to display.

Count observations with geom_bar()

ggplot(mpg, aes(x = class)) +
  geom_bar(fill = "steelblue") +
  labs(x = "Vehicle class", y = "Number of vehicles") +
  theme_minimal()

Display precomputed values with geom_col()

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

ggplot(class_summary, aes(class, mean_hwy)) +
  geom_col(fill = "steelblue") +
  coord_flip() +
  labs(x = "Vehicle class", y = "Mean highway mpg") +
  theme_minimal()
ggplot2 bar chart comparing average highway fuel economy in miles per gallon across vehicle classes
Mean highway fuel economy by vehicle class, calculated before plotting. Download bar chart image.

Histograms: visualize numerical distributions

A histogram divides a numerical variable into intervals called bins and counts the observations in each interval. The bin width affects the apparent shape of the distribution.

ggplot(mpg, aes(x = hwy)) +
  geom_histogram(binwidth = 3, fill = "steelblue",
                 colour = "white") +
  labs(
    title = "Distribution of highway fuel economy",
    x = "Highway fuel economy (mpg)",
    y = "Number of vehicles"
  ) +
  theme_minimal()
ggplot2 histogram showing the frequency distribution of highway fuel economy for observations in the mpg dataset
Histogram of highway fuel economy. Experiment with binwidth to change the level of detail. Download histogram image.

Boxplots: compare distributions across groups

A boxplot summarizes a distribution using its median, quartiles and whiskers. Points beyond the whiskers may be displayed as potential outliers under the boxplot rule.

ggplot(mpg, aes(class, hwy, fill = class)) +
  geom_boxplot(show.legend = FALSE) +
  labs(
    title = "Highway fuel economy by vehicle class",
    x = "Vehicle class",
    y = "Highway fuel economy (mpg)"
  ) +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 35, hjust = 1))
ggplot2 boxplots comparing highway fuel economy distributions across vehicle classes
Compare medians, interquartile ranges and potential outliers across vehicle classes. Download boxplot image.

Line graphs: visualize ordered observations

Line graphs are appropriate when observations have a meaningful order, commonly time. The following example summarizes fuel economy by model year and vehicle class before connecting the values.

year_summary <- mpg |>
  dplyr::group_by(year, class) |>
  dplyr::summarise(mean_hwy = mean(hwy), .groups = "drop")

ggplot(year_summary,
       aes(year, mean_hwy, colour = class, group = class)) +
  geom_line() +
  geom_point() +
  labs(x = "Model year", y = "Mean highway mpg",
       colour = "Vehicle class") +
  theme_minimal()
ggplot2 line chart showing average highway fuel economy by model year for several vehicle classes
Grouped line chart of average highway fuel economy by model year. Download line chart image.

Density plots: compare distribution shapes

A density plot displays a smoothed estimate of a numerical distribution. It can be useful for comparing distribution shapes across groups, although the bandwidth affects the smoothness of the curve.

ggplot(mpg, aes(hwy, colour = drv, fill = drv)) +
  geom_density(alpha = 0.2) +
  labs(x = "Highway fuel economy (mpg)",
       y = "Density", colour = "Drivetrain",
       fill = "Drivetrain") +
  theme_minimal()
Overlaid ggplot2 density curves comparing highway fuel economy distributions for front, rear and four-wheel drive vehicles
Density curves compare the distribution shapes for drivetrain groups. Download density plot image.

For detailed chart-specific explanations, see the dedicated scatter plot, bar chart, histogram, line graph, boxplot and density and violin plot lessons.

Statistical Transformations in ggplot2

Some geoms display observations as supplied, while others calculate a summary or transformation before drawing. These calculations are called statistical transformations, often shortened to stats.

Common statistical transformations

  • stat_count() counts observations in categories; it is used by geom_bar() by default.
  • stat_bin() divides numerical values into bins; it is used by geom_histogram().
  • stat_smooth() fits a model or smoother; it is used by geom_smooth().
  • stat_summary() calculates summaries such as means or confidence intervals.
  • stat_identity() uses supplied values without a statistical transformation; it is used by geom_col().

Add a linear regression line with geom_smooth()

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

The shaded region is the standard-error confidence band when se = TRUE. A fitted trend describes a pattern in the observed data; it does not, by itself, demonstrate causation.

Calculate group means with stat_summary()

ggplot(mpg, aes(class, hwy)) +
  stat_summary(fun = mean, geom = "col",
               fill = "steelblue") +
  stat_summary(fun.data = mean_se, geom = "errorbar",
               width = 0.2) +
  labs(x = "Vehicle class", y = "Mean highway mpg") +
  theme_minimal()

Scales, Axes and Coordinate Systems

Scales translate data values into visual values. They control axes, colours, fills, sizes and legends. Coordinate systems control how positions are displayed in the plotting area. These are distinct parts of a ggplot.

Continuous and discrete scales

Continuous scales are commonly used for numerical variables such as displacement and fuel economy. Discrete scales are commonly used for categories such as vehicle class and drivetrain.

# Control numerical axis breaks
ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  scale_x_continuous(
    breaks = seq(1, 7, by = 1),
    name = "Engine displacement (litres)"
  )

# Set colours for drivetrain categories
ggplot(mpg, aes(displ, hwy, colour = drv)) +
  geom_point() +
  scale_colour_manual(
    values = c("4" = "#3B75AF",
               "f" = "#E07B39",
               "r" = "#4B9B73")
  )

Coordinate systems and zooming

# Flip the coordinate system
ggplot(mpg, aes(class)) +
  geom_bar() +
  coord_flip()

# Zoom into a region without dropping observations
ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  coord_cartesian(xlim = c(2, 6), ylim = c(10, 35))

When you only want to zoom the display, coord_cartesian() is generally preferable to setting scale limits, because scale limits can remove observations before some statistical transformations are calculated.

Faceting: Create Multiple Panels in ggplot2

Faceting divides a dataset into subsets and displays each subset in its own panel. It is useful for comparing relationships across categories while retaining a consistent chart design.

Use facet_wrap() for one grouping variable

ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  facet_wrap(~ drv) +
  labs(
    title = "Engine size and fuel economy by drivetrain",
    x = "Engine displacement (litres)",
    y = "Highway fuel economy (mpg)"
  ) +
  theme_minimal()
Faceted ggplot2 scatter plots showing engine displacement versus highway fuel economy in separate panels for front-wheel, rear-wheel and four-wheel drive vehicles
Small multiples separate observations by drivetrain while retaining a common chart structure. Download faceted chart image.

Use facet_grid() for two grouping variables

ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  facet_grid(drv ~ year) +
  theme_minimal()

When should you use facets?

  • When too many groups overlap in a single chart.
  • When you want to compare the same relationship across categories.
  • When small multiples make subgroup patterns easier to interpret.

Themes and Styling in ggplot2

Themes control non-data elements such as backgrounds, grid lines, text, axis titles, tick labels and legend placement. A theme changes the presentation of a plot, not the underlying observations or statistical calculations.

Built-in ggplot2 themes

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

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

Customize theme elements

p +
  theme_minimal() +
  theme(
    plot.title = element_text(size = 16, face = "bold"),
    axis.title = element_text(size = 12),
    axis.text = element_text(size = 10),
    panel.grid.minor = element_blank(),
    legend.position = "bottom"
  )

Choose a theme that supports the message rather than distracting from it. Keep typography readable, use a restrained palette and apply consistent styling across related charts. See the dedicated ggplot2 themes lesson for further customization.

Titles, Axis Labels and Annotations

Clear labels help readers understand what a chart measures. The labs() function sets the title, subtitle, axis labels, legend titles and caption. Annotation functions can add reference lines, text or other contextual information.

Add titles, subtitles and captions with labs()

ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  labs(
    title = "Engine displacement and highway fuel economy",
    subtitle = "Vehicle observations from the mpg dataset",
    x = "Engine displacement (litres)",
    y = "Highway fuel economy (miles per gallon)",
    caption = "Source: ggplot2 mpg dataset"
  ) +
  theme_minimal()

Add a reference line and annotation

ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  geom_hline(yintercept = 25, linetype = "dashed",
             colour = "firebrick") +
  annotate("text", x = 6, y = 26,
           label = "25 mpg reference", hjust = 1) +
  theme_minimal()

Use annotations selectively. Each label should help readers interpret the data, identify an important value or understand the context.

A Complete Data Visualization Workflow with ggplot2

In practical analysis, visualization is part of a wider workflow. Inspect the data, check missing values and variable types, prepare the variables, choose a chart that answers the question, then refine the labels and presentation. This example combines dplyr for data preparation and ggplot2 for visualization.

Step 1: Prepare and summarize the data

library(dplyr)
library(ggplot2)

class_summary <- mpg |>
  group_by(class) |>
  summarise(
    vehicles = n(),
    mean_hwy = mean(hwy, na.rm = TRUE),
    sd_hwy = sd(hwy, na.rm = TRUE),
    .groups = "drop"
  ) |>
  arrange(desc(mean_hwy))

class_summary

Step 2: Create the visualization

ggplot(class_summary,
       aes(x = reorder(class, mean_hwy), y = mean_hwy)) +
  geom_col(fill = "steelblue", width = 0.75) +
  coord_flip() +
  labs(
    title = "Average highway fuel economy by vehicle class",
    subtitle = "Mean highway miles per gallon",
    x = "Vehicle class",
    y = "Mean highway fuel economy (mpg)"
  ) +
  theme_minimal()

Step 3: Interpret and validate the chart

  • Check whether the chart answers the original analytical question.
  • Confirm that the aggregation is appropriate and missing values are handled deliberately.
  • Check category ordering and axis units.
  • Look for misleading scales, crowded labels or unnecessary decoration.
  • Use consistent definitions and units when comparing charts.

This workflow illustrates the relationship between the two packages: dplyr prepares and summarizes the data, while ggplot2 maps the resulting columns to visual properties. Continue with the dplyr tutorial for filtering, grouping, joining and transforming data.

Save and Export ggplot2 Charts

Use ggsave() to save the last displayed plot or a named plot object. Common formats include PNG for general digital use, PDF for vector output and SVG for scalable web graphics.

Save the last displayed plot

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

ggsave("scatter-plot.png",
       width = 8, height = 5, dpi = 300)

Save a named plot object

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

# High-resolution PNG
ggsave("scatter-plot.png", plot = p,
       width = 8, height = 5, dpi = 300)

# PDF vector output
ggsave("scatter-plot.pdf", plot = p,
       width = 8, height = 5)

# SVG vector output
ggsave("scatter-plot.svg", plot = p,
       width = 8, height = 5)

Understand dimensions and resolution

  • Width and height: set the physical dimensions of the exported chart.
  • dpi: controls raster resolution for formats such as PNG. A higher value is useful for print-quality raster images.
  • Vector formats: PDF and SVG preserve scalable paths and are useful for many publication and design workflows.

See the dedicated ggplot2 save and export lesson for more examples.

Complete ggplot2 Tutorial: Lessons and Topics

The main tutorial introduces the overall workflow. The supporting lessons focus on narrower topics with additional code, options and examples. Follow them in order if you are new to ggplot2, or open the topic you need.

Foundations

Chart types

Customization and advanced plotting

Quick reference

ggplot2 vs Base R Graphics

Base R graphics are included with R and are useful for quick exploratory plots. ggplot2 uses a layered grammar that makes it convenient to build complex charts from reusable components. The right choice depends on the task and the requirements of the analysis.

TaskBase Rggplot2
Scatter plotplot(mpg$displ, mpg$hwy)ggplot(mpg, aes(displ, hwy)) + geom_point()
Histogramhist(mpg$hwy)ggplot(mpg, aes(hwy)) + geom_histogram()
Boxplot by groupboxplot(hwy ~ class, data = mpg)ggplot(mpg, aes(class, hwy)) + geom_boxplot()
Bar countsbarplot(table(mpg$class))ggplot(mpg, aes(class)) + geom_bar()

Which approach should you learn?

Learn enough base graphics to create and understand quick exploratory plots. Use ggplot2 when you need a consistent, extensible plotting workflow with mappings, layers, facets and reusable themes. Many R analysts use both.

Common ggplot2 Errors and How to Fix Them

Could not find function ggplot

Cause: ggplot2 has not been loaded in the current R session.

library(ggplot2)

Object not found

Cause: a column name is misspelled, the wrong data frame is supplied, or the variable is absent from a layer's data.

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

Bars show counts instead of supplied values

Cause: geom_bar() counts observations by default. Use geom_col() when the data already contain the values to display.

# Counts
ggplot(mpg, aes(class)) + geom_bar()

# Supplied values
summary_data <- data.frame(
  group = c("A", "B", "C"),
  value = c(12, 18, 15)
)
ggplot(summary_data, aes(group, value)) + geom_col()

An unexpected legend appears

Cause: a fixed visual setting may have been placed inside aes(). Put fixed values outside aes(); use mappings inside it when a data variable should control the visual property.

Points overlap and hide observations

Solutions: reduce point size, use transparency with alpha, apply jitter where appropriate, or consider a density or binned chart.

ggplot(mpg, aes(displ, hwy)) +
  geom_point(alpha = 0.35, size = 1.5)

Category labels overlap

Solutions: rotate axis labels, flip coordinates, shorten category names or use facets.

ggplot(mpg, aes(class, hwy)) +
  geom_boxplot() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

Zooming changes a statistical result

Cause: scale limits can remove observations before statistical calculations. Use coord_cartesian() when you want to zoom the view while retaining observations for statistical transformations.

ggplot2 Best Practices for Clear Data Visualization

Choose a chart that matches the analytical question

Use scatter plots for relationships between numerical variables, histograms for numerical distributions, bar charts for category counts or summaries, boxplots for comparing distributions and line charts for ordered observations.

Use visual mappings consistently

Avoid mapping too many variables to colour, shape and size at once. Use consistent mappings across related charts and make sure legends explain the visual encodings.

Label units and provide context

Axis titles should identify the variable and its unit. A descriptive title, subtitle or caption can explain the population, period or data source. Avoid vague labels such as "Value" when a more informative label is available.

Keep the design readable

Use readable text, a restrained colour palette and a clear background. Remove decorative elements that do not help interpretation. Check the graphic at the size at which readers will view it.

Check data quality and statistical meaning

Inspect missing values, outliers, category definitions and aggregation choices. A chart can be attractive and still be misleading if it uses an unsuitable summary, scale or grouping.

Make charts reproducible

Keep plotting code with the analysis, use clearly named data objects and save figures with explicit dimensions and output formats. This makes graphics easier to update when data change.

Related R learning: For data cleaning, filtering, grouping, joining and summarizing before visualization, continue with our dplyr tutorial. Use dplyr and ggplot2 together as part of a complete R data analysis workflow.

ggplot2 FAQ

What is ggplot2 in R?

ggplot2 is an R package for creating data visualizations using a layered system based on the grammar of graphics. A plot combines data, aesthetic mappings, geometric objects, statistical transformations, scales, coordinate systems and themes.

Is this ggplot2 tutorial suitable for beginners?

Yes. It starts with installation, ggplot(), aes() and basic layers, then progresses to chart types and customization. Basic familiarity with R objects and data frames is helpful.

How do I install ggplot2 in R?

Run install.packages("ggplot2") once, then load it in each new R session with library(ggplot2).

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

geom_bar() counts observations by default. geom_col() displays values already present in the data.

What is the difference between aes() and fixed settings?

aes() maps a data variable to a visual property such as colour, size or shape. A setting outside aes(), such as colour = "steelblue", applies one fixed value to the layer.

Which dataset is used in this tutorial?

Most examples use the built-in ggplot2 mpg dataset, which contains 234 vehicle observations and variables such as engine displacement, drivetrain, vehicle class and fuel economy.

Can ggplot2 create publication-quality graphics?

Yes. You can customize scales, labels, annotations, themes, dimensions and output formats to create clear graphics for reports, presentations and research.

Is ggplot2 part of the tidyverse?

Yes. ggplot2 is a core tidyverse package and works particularly well with dplyr for preparing data before visualization.

Is ggplot2 free?

Yes. ggplot2 is open-source software distributed under the MIT license and is available from CRAN.

To continue learning, start with ggplot2 basics, then explore the individual chart tutorials and the ggplot2 cheat sheet.