R ggplot2
last modified November 19, 2026
ggplot2 builds plots from three ingredients: a data set, a mapping from
variables to visual properties, and one or more geometric objects that draw
the marks. The mapping is written with aes, the geometry with a
function such as geom_point or geom_line, and the
layers are joined with the plus operator. This grammar makes a scatter plot,
a line chart, and a histogram differ only in the geometry, while the data and
the mapping stay the same. This article covers scatter plots, aesthetic
mappings, lines, bars, histograms, boxplots, and a combined plot. The examples
use ggplot2 4.0.4 with R 4.5.2, and each script writes a PNG file so the
output block can stay numeric.
The examples need the ggplot2 package, which is not part of base R. Install it
once with install.packages("ggplot2"); the
installing packages section of the
introduction explains the details.
The grammar of graphics
The mtcars data set records fuel consumption and ten design
features for thirty-two cars. A scatter plot of miles per gallon against
weight starts with ggplot, maps wt to the x position
and mpg to the y position, and adds geom_point.
ggsave writes the result to a file at a chosen size.
library(ggplot2)
p <- ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point()
ggsave("scatter.png", p, width = 5, height = 3.5, dpi = 72)
cat("cars:", nrow(mtcars), "\n")
cat("correlation:", round(cor(mtcars$wt, mtcars$mpg), 3), "\n")
The plot shows the expected downward pattern: heavier cars travel fewer miles
per gallon, and the correlation is -0.868. The axes are labelled with the
variable names and the tick positions are chosen automatically. Nothing was
drawn until the geometry was added, because ggplot alone only
creates the coordinate system and the mapping. The PNG is 360 by 252 pixels,
which is five by three and a half inches at 72 dots per inch.
$ Rscript scatter.R cars: 32 correlation: -0.868
Mapping aesthetics
Position is only one aesthetic. Colour, size, shape, and transparency can also be mapped to variables, and ggplot2 builds a legend for each mapped property. A variable that should split the data into groups is usually converted to a factor first, because a numeric colour mapping produces a continuous gradient rather than one colour per group.
library(ggplot2)
cars <- mtcars
cars$cylinders <- factor(cars$cyl)
p <- ggplot(cars, aes(x = wt, y = mpg, colour = cylinders, size = hp)) +
geom_point()
ggsave("aesthetics.png", p, width = 5, height = 3.5, dpi = 72)
print(table(cars$cylinders))
cat("hp range:", range(cars$hp), "\n")
The cars split into eleven four-cylinder, seven six-cylinder, and fourteen
eight-cylinder models, and each group receives its own colour. Horsepower
drives the point size and ranges from 52 to 335, so the legend shows a few
representative values rather than one entry per car. The two legends sit to
the right of the panel. A constant colour would be written outside
aes, as in colour = "blue", because a mapping
describes a variable and a setting describes a fixed value.
$ Rscript aesthetics.R 4 6 8 11 7 14 hp range: 52 335
Line charts
geom_line connects the observations in row order, so the data
must be sorted by the variable on the x axis. The economics data
set in ggplot2 records monthly unemployment and other indicators for the
United States. Its date column has the Date class,
which ggplot2 recognises and formats automatically.
library(ggplot2)
p <- ggplot(economics, aes(x = date, y = unemploy)) +
geom_line(linewidth = 1)
ggsave("line.png", p, width = 5, height = 3.5, dpi = 72)
cat("months:", nrow(economics), "\n")
cat("first:", format(min(economics$date)), "\n")
cat("last:", format(max(economics$date)), "\n")
The series covers 574 months from July 1967 to April 2015. The line thickness
is set with linewidth rather than size, which is the
aesthetic used for lines since ggplot2 3.4. The x axis prints decade labels
instead of one label per month, and the y axis reports unemployment in
thousands. Because the rows are already in date order, no sorting is needed;
shuffling the rows would produce a zigzag line that connects unrelated
months.
$ Rscript line-chart.R months: 574 first: 1967-07-01 last: 2015-04-01
Bars
geom_bar counts the rows for every x value and draws one bar per
count. It needs only an x mapping, because the height is computed from the
data. The alternative geom_col takes an explicit y mapping when
the counts have already been computed.
library(ggplot2)
cars <- mtcars
cars$cyl <- factor(cars$cyl)
p <- ggplot(cars, aes(x = cyl)) +
geom_bar()
ggsave("bar.png", p, width = 5, height = 3.5, dpi = 72)
print(table(cars$cyl))
The bars show the same counts as table: eleven cars with four
cylinders, seven with six, and fourteen with eight. Converting the cylinder
count to a factor puts the three values on a categorical axis and gives each
bar an equal width. The y axis is labelled count by default,
because the height was computed rather than mapped. A bar chart of a numeric
variable without the factor conversion would use a continuous axis and place
the bars at 4, 6, and 8.
$ Rscript bar.R 4 6 8 11 7 14
Histograms
A histogram bins a continuous variable and draws a bar for the number of
observations in each bin. binwidth sets the width of the bins in
the units of the variable, and bins sets their number when the
width is not given. The outline colour makes neighbouring bars easier to tell
apart.
library(ggplot2)
p <- ggplot(mtcars, aes(x = mpg)) +
geom_histogram(binwidth = 5, colour = "white")
ggsave("histogram.png", p, width = 5, height = 3.5, dpi = 72)
cat("mean:", round(mean(mtcars$mpg), 2), "\n")
cat("sd:", round(sd(mtcars$mpg), 2), "\n")
cat("range:", range(mtcars$mpg), "\n")
The fuel consumption averages 20.09 miles per gallon with a standard deviation of 6.03, and the values run from 10.4 to 33.9. With a bin width of five, the bins start at ten and cover the range in five steps. The shape is skewed to the right, with a cluster of economical cars and a long tail of heavy models. Changing the bin width changes the shape, so the width should be chosen deliberately rather than left to the default.
$ Rscript histogram.R mean: 20.09 sd: 6.03 range: 10.4 33.9
Boxplots
A boxplot summarises a numeric variable for each group. The box runs from the first quartile to the third, the line inside marks the median, and the whiskers reach the most extreme observations within one and a half times the interquartile range. Points beyond the whiskers are drawn individually as outliers.
library(ggplot2)
cars <- mtcars
cars$cyl <- factor(cars$cyl)
p <- ggplot(cars, aes(x = cyl, y = mpg)) +
geom_boxplot()
ggsave("boxplot.png", p, width = 5, height = 3.5, dpi = 72)
print(tapply(cars$mpg, cars$cyl, median))
The median fuel consumption falls from 26.0 for four-cylinder cars to 19.7 for
six and 15.2 for eight. The four-cylinder group also has the widest box, while
the eight-cylinder group is more concentrated. One high outlier appears in the
six-cylinder group. The medians match the tapply result, which is
a useful check that the plot and the summary agree.
$ Rscript box-plots.R 4 6 8 26.0 19.7 15.2
A complete example
The final script adds a second layer to the scatter plot. geom_point
draws the observations and geom_smooth draws a fitted line from
the same mapping. Setting method = "lm" chooses a straight line,
formula = y ~ x states the model, and se = FALSE
leaves out the confidence band.
library(ggplot2)
p <- ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point() +
geom_smooth(method = "lm", formula = y ~ x, se = FALSE)
ggsave("report.png", p, width = 5, height = 3.5, dpi = 72)
fit <- lm(mpg ~ wt, data = mtcars)
print(round(coef(fit), 2))
cat("r squared:", round(summary(fit)$r.squared, 3), "\n")
The fitted line has an intercept of 37.29 and a slope of -5.34, so every extra thousand pounds costs about 5.3 miles per gallon. The model explains 0.753 of the variation in fuel consumption. The plot shows the same numbers visually: the line passes through the middle of the cloud and the points scatter around it. Layers are drawn in the order they are added, so a later geometry sits on top of an earlier one.
$ Rscript report.R
(Intercept) wt
37.29 -5.34
r squared: 0.753
Next steps
The base graphics article draws the same
kinds of figures with the older plot, hist, and
boxplot functions, which is useful when a package must not add
dependencies. The dplyr article shows how to
prepare the grouped summaries that a bar chart or a boxplot displays, and the
tidyr article reshapes data into the long form that
ggplot2 expects for grouped series. The next article,
customizing ggplot2 figures, adds
facets, scales, labels, and themes to these plots. The
packages article explains how to install
ggplot2 and check its version.
Source
ggplot2 reference: geom_histogram
ggplot2 reference: geom_boxplot
In this article we have built scatter plots from a data set, an aesthetic mapping, and a geometry. We mapped colour and size to variables, drew a monthly line chart, and counted categories with bars. We binned a continuous variable into a histogram, compared groups with boxplots, and added a regression layer on top of a point layer. Each figure was written to a PNG file, and the printed numbers confirmed what the plot showed. The series continues with R ggplot2 customization.
Author
List all R Language tutorials.