R ggplot2 customization
last modified November 19, 2026
The ggplot2 article builds a plot from data, a
mapping, and a geometry. A default plot is readable but generic: one panel
holds every group, the axes choose their own limits, and the legend sits on
the right. This article changes those defaults. Facets split a plot into
small multiples, scales control the values and the colours, labs
and annotate put text into the figure, theme styles
everything that is not data, and position adjustments decide how overlapping
marks share space. The examples use ggplot2 4.0.4 with R 4.5.2 and write each
figure to a PNG file.
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.
Facets
A facet splits the data by one or more variables and draws a panel for each
group. facet_wrap lays the panels out in a rectangle and wraps
them into rows, while facet_grid arranges them in a fixed grid of
rows and columns. The argument is a formula, so ~ cyl means one
panel per value of cyl. Both functions accept
labeller to change the panel titles.
library(ggplot2)
cars <- mtcars
cars$cyl <- factor(cars$cyl)
p <- ggplot(cars, aes(x = wt, y = mpg)) +
geom_point() +
facet_wrap(~ cyl, nrow = 1)
ggsave("facets.png", p, width = 6, height = 2.8, dpi = 72)
print(table(cars$cyl))
cat("panels:", nlevels(cars$cyl), "\n")
The thirty-two cars split into eleven with four cylinders, seven with six,
and fourteen with eight, and the plot contains one panel per group.
nrow = 1 puts the three panels in a single row, which suits a
wide figure. Every panel keeps the same axis ranges by default, so the panels
can be compared directly; scales = "free" would let each panel
choose its own limits. The downward pattern is visible in all three groups,
but the four-cylinder cars cluster at the low end of the weight axis.
$ Rscript facets.R 4 6 8 11 7 14 panels: 3
Scales and limits
A scale maps a data value to a visual property: a position on an axis, a
colour, a size, or a shape. Each scale has a default that suits most data, and
each can be replaced by a function whose name starts with scale_
and ends with the aesthetic. scale_colour_manual takes a named
vector of colours, so the names must match the factor levels exactly.
library(ggplot2)
cars <- mtcars
cars$cyl <- factor(cars$cyl)
p <- ggplot(cars, aes(x = wt, y = mpg, colour = cyl)) +
geom_point(size = 2) +
scale_colour_manual(values = c("4" = "#1b9e77",
"6" = "#d95f02",
"8" = "#7570b3")) +
scale_x_continuous(limits = c(1, 6), breaks = seq(1, 6, 1)) +
scale_y_continuous(breaks = seq(15, 30, 5)) +
coord_cartesian(ylim = c(15, 30))
ggsave("scales.png", p, width = 5, height = 3.5, dpi = 72)
cat("weight range:", range(cars$wt), "\n")
cat("outside view:", sum(cars$mpg < 15 | cars$mpg > 30), "\n")
cat("rows in data:", nrow(cars), "\n")
The weights run from 1.513 to 5.424 thousand pounds, so the x limits keep
every car, and the y view shows twenty-three of the thirty-two: nine cars
fall outside the range from 15 to 30 miles per gallon. The distinction
between coord_cartesian and a scale limit matters. A limit in
scale_y_continuous removes the rows before plotting, and ggplot2
reports how many it dropped; coord_cartesian keeps all rows and
only changes the visible window, which is the right choice for zooming. The
legend lists the three factor levels with their assigned colours.
$ Rscript scales.R weight range: 1.513 5.424 outside view: 9 rows in data: 32
Labels and annotations
labs sets the title, the subtitle, the axis labels, and the
caption in one call. The axis titles can also be set with xlab
and ylab, and the title with ggtitle, but
labs keeps the names together. annotate adds a
single text label or shape at a given position, which is useful for marking a
threshold that was computed from the data.
library(ggplot2)
p <- ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point(colour = "grey30") +
geom_hline(yintercept = mean(mtcars$mpg),
linetype = "dashed", colour = "firebrick") +
annotate("text", x = 5.2, y = mean(mtcars$mpg) + 1.2,
label = "mean mpg", colour = "firebrick") +
labs(title = "Fuel consumption and weight",
subtitle = "32 car models from 1974",
x = "Weight (1000 lbs)",
y = "Miles per gallon",
caption = "Source: mtcars")
ggsave("labels.png", p, width = 5.5, height = 3.8, dpi = 72)
cat("mean mpg:", round(mean(mtcars$mpg), 2), "\n")
cat("lightest car:", min(mtcars$wt), "\n")
The dashed line marks the mean fuel consumption of 20.09 miles per gallon, and
the label beside it says what the line represents. The
caption in the lower right records where the data came from. A computed
position such as mean(mtcars$mpg) keeps the annotation attached
to the data; a hard-coded number would silently drift away after the data
changed. The default grey theme is left in place here, because the next
section replaces it with a styled variant.
$ Rscript plot-labels.R mean mpg: 20.09 lightest car: 1.513
Themes
A theme controls the parts of the figure that are not data: backgrounds,
grids, fonts, and the legend. theme_minimal,
theme_bw, and theme_classic are ready-made themes
that accept base_size and base_family. The
theme function then overrides individual elements, and an
element set to element_blank() disappears.
library(ggplot2)
cars <- mtcars
cars$cyl <- factor(cars$cyl)
p <- ggplot(cars, aes(x = cyl, fill = cyl)) +
geom_bar() +
labs(x = "Cylinders", y = "Models") +
theme_minimal(base_size = 13) +
theme(legend.position = "none",
panel.grid.major.x = element_blank(),
panel.grid.minor = element_blank(),
axis.text = element_text(colour = "grey20"))
ggsave("theme.png", p, width = 5, height = 3.5, dpi = 72)
print(table(cars$cyl))
cat("models:", nrow(cars), "\n")
The base font size rises from 11 to 13 points, which scales every text element
in the figure. Vertical grid lines are removed because the bars already mark
the categories, the minor grid is removed entirely, and the axis text becomes
dark grey instead of the default black. The legend is redundant when the x
axis already shows the same three values as the fill, so
legend.position = "none" drops it. A theme set inside a plot
affects that plot only; theme_set would change the default for
the whole session.
$ Rscript plot-themes.R 4 6 8 11 7 14 models: 32
Positions
When several rows map to the same x value, a position adjustment decides how
their marks share the space. The default for bars is "stack",
which puts the counts on top of each other. position_dodge places
them side by side, and position_fill stacks them to a common
height and shows proportions. A small width value leaves a gap
between the groups.
library(ggplot2)
cars <- mtcars
cars$cyl <- factor(cars$cyl)
cars$gear <- factor(cars$gear)
p <- ggplot(cars, aes(x = gear, fill = cyl)) +
geom_bar(position = position_dodge(width = 0.8)) +
scale_fill_brewer(palette = "Set2") +
labs(x = "Gears", y = "Models", fill = "Cylinders")
ggsave("positions.png", p, width = 5, height = 3.5, dpi = 72)
print(table(cars$gear, cars$cyl))
Twelve of the fifteen cars with three gears have eight cylinders, while the
four-gear group is dominated by four-cylinder models, and the five-gear group
is the smallest. The dodged bars make those counts visible side by side; a
stacked chart would show the same numbers as one bar per gear and make the
small groups harder to compare. scale_fill_brewer chooses a
qualitative palette from RColorBrewer, which is designed for categories and
stays readable in print.
$ Rscript positions.R
4 6 8
3 1 2 12
4 8 4 0
5 2 1 2
A complete example
The last script combines the four ideas. The data is faceted by gearbox, the
points are coloured by cylinder with a brewer palette, the labels and the
caption are set with labs, and the theme places the legend at the
bottom. labeller = label_both writes the variable name in front of
each panel value, so a reader who sees one panel alone still knows what its
number means.
library(ggplot2)
cars <- mtcars
cars$cyl <- factor(cars$cyl, levels = c(4, 6, 8))
cars$gear <- factor(cars$gear)
p <- ggplot(cars, aes(x = wt, y = mpg, colour = cyl)) +
geom_point(size = 2) +
geom_smooth(method = "lm", formula = y ~ x,
se = FALSE, linewidth = 0.6) +
facet_wrap(~ gear, nrow = 1, labeller = label_both) +
scale_colour_brewer(palette = "Dark2", name = "Cylinders") +
labs(title = "Weight and fuel consumption",
subtitle = "Three gearbox groups",
x = "Weight (1000 lbs)",
y = "Miles per gallon",
caption = "Source: mtcars") +
theme_bw(base_size = 11) +
theme(legend.position = "bottom")
ggsave("report.png", p, width = 7, height = 3.2, dpi = 100)
cat("file size:", file.size("report.png"), "bytes\n")
print(round(tapply(cars$mpg, cars$gear, mean), 2))
The plot is 700 by 320 pixels at 100 dots per inch and takes 36308 bytes. The mean fuel consumption is 16.11 miles per gallon for three gears, 24.53 for four, and 21.38 for five. The four-gear group has the highest mean because it is dominated by light four-cylinder cars, while the three-gear group holds mostly heavy eight-cylinder models. Each panel fits its own least-squares line, and panels with a single point in a colour group get no line for that group. The printed means summarise the same data that the panels show.
$ Rscript report.R
file size: 36308 bytes
3 4 5
16.11 24.53 21.38
Next steps
The exporting plots article takes the same figures and writes them to PNG, PDF, and SVG files at chosen sizes and resolutions, which is the next question after a plot looks right on screen. The ggplot2 article covers the geoms and the grammar that this article customizes, and the base graphics article shows the older system that needs no package at all.
Source
ggplot2 reference: manual scales
ggplot2 reference: coord_cartesian
ggplot2 reference: position_dodge
In this article we have split a plot into faceted panels, replaced automatic scales with manual colours, and zoomed a view without removing data. We added a title, a subtitle, a caption, and an annotation tied to a computed value, then styled the figure with a minimal theme. Dodged bars compared two categorical variables, and the final plot combined facets, scales, labels, and a theme in one file. The series continues with R exporting plots.
Author
List all R Language tutorials.