R base graphics
last modified November 19, 2026
R has two graphics systems. The base system ships with every installation and draws a plot with a single function call, while ggplot2 builds plots from layers and needs a package. Base graphics are the quicker choice for a first look at data and the foundation on which many packages are built. This article covers scatter plots, line charts, histograms, boxplots, bar charts, pie charts, and the parameters that arrange several plots on one page. Every example writes its figure to a PNG file, and the output block reports a short numeric summary of the data behind the plot.
A scatter plot
plot chooses a sensible display from the type of its arguments.
Two numeric vectors produce a scatter plot, with the first vector on the
horizontal axis and the second on the vertical axis. The arguments
main, xlab, and ylab set the title and
the axis labels, and pch and col set the point
symbol and its colour.
hours <- c(2, 3, 5, 6, 8, 9, 11, 12)
scores <- c(55, 62, 68, 74, 79, 85, 88, 94)
png("scatter.png", width = 600, height = 400)
plot(hours, scores, pch = 19, col = "steelblue",
main = "Study time and score",
xlab = "Hours", ylab = "Score")
invisible(dev.off())
cat("plotted points:", length(hours), "\n")
The call opens a PNG device, draws the plot, and closes the device with
dev.off, wrapped in invisible so that its return
value does not print. Closing the device is what writes the file, so it must
not be skipped. The points rise from the lower left to the upper right, which
is the shape a positive relationship produces.
$ Rscript scatter.R plotted points: 8
Lines and points
The argument type = "l" connects the observations with a line,
which suits a sequence ordered in time. points adds markers to an
existing plot, lines adds another line, and abline
draws a straight line defined by a slope and an intercept or by a horizontal
or vertical position.
x <- 1:10
y <- c(3, 5, 4, 7, 8, 7, 9, 11, 10, 12)
png("lines.png", width = 600, height = 400)
plot(x, y, type = "l", lwd = 2, col = "darkgreen",
main = "A line chart", xlab = "Day", ylab = "Value")
points(x, y, pch = 19, col = "darkgreen")
abline(h = mean(y), lty = 2, col = "gray40")
invisible(dev.off())
cat("mean value:", mean(y), "\n")
The line shows the day-to-day movement, the points mark the actual
observations, and the dashed horizontal line marks the mean of 7.6. A line
chart implies that the points are connected in a meaningful order, so it
should not be used for categories that have no sequence. The width of the line
comes from lwd, and the dash pattern from lty.
$ Rscript lines-points.R mean value: 7.6
Histograms
hist divides the range of a numeric vector into bins and counts
the values in each bin. The result is a bar chart of frequencies, which shows
the shape of the distribution: where it is centred, how wide it is, and
whether it has a second peak. The function returns the breaks, the counts, and
the midpoints of the bins.
set.seed(5)
scores <- rnorm(200, mean = 70, sd = 10)
png("histogram.png", width = 600, height = 400)
h <- hist(scores, breaks = 10, col = "lightblue", border = "white",
main = "Distribution of scores", xlab = "Score")
invisible(dev.off())
print(h$counts)
cat("bins:", length(h$counts), "\n")
The breaks argument is a suggestion rather than a command: R
adjusts it to produce round cut points, which is why twelve bins appear
instead of ten. The counts rise to a peak of 47 and then fall, and the
distribution is roughly symmetric around 70. The colours and the border
argument only affect the appearance, not the counts.
$ Rscript histogram.R [1] 1 3 8 19 29 47 30 32 19 6 5 1 bins: 12
Boxplots
A boxplot summarises a distribution with its median, its quartiles, and its whiskers. The box covers the middle half of the data, the thick line inside is the median, and the whiskers extend to the most extreme values that are not outliers. Points beyond the whiskers are drawn individually.
set.seed(9)
scores <- list(
math = rnorm(30, 70, 10),
art = rnorm(30, 75, 8),
music = rnorm(30, 72, 12)
)
png("boxplot.png", width = 600, height = 400)
b <- boxplot(scores, col = c("lightblue", "lightgreen", "lavender"),
main = "Scores by subject", ylab = "Score")
invisible(dev.off())
print(b$stats)
print(b$names)
Passing a named list draws one box per element and labels the axis with the
names. The returned stats matrix has one column per group and
five rows: the lower whisker, the lower quartile, the median, the upper
quartile, and the upper whisker. The music group has the widest box and
therefore the largest interquartile range, while art and music have nearly the
same median, with music slightly ahead.
$ Rscript box-plots.R
[,1] [,2] [,3]
[1,] 58.13127 58.84495 48.45098
[2,] 63.06668 68.13179 62.29128
[3,] 68.90508 73.38749 73.62045
[4,] 74.36307 78.04891 78.55293
[5,] 88.45257 92.84367 90.77954
[1] "math" "art" "music"
Bar charts
barplot draws one bar per value of a vector, which is the right
choice for counts that belong to categories. The function returns the
horizontal midpoint of each bar, and those positions can be passed to
text to write a label on top of every bar.
counts <- c(math = 12, art = 9, music = 7)
png("barplot.png", width = 600, height = 400)
bp <- barplot(counts, col = "steelblue", main = "Students per subject",
ylab = "Students", ylim = c(0, 14))
text(bp, counts + 0.5, labels = counts)
invisible(dev.off())
print(bp)
print(counts)
The midpoints are 0.7, 1.9, and 3.1, evenly spaced because the bars have equal
width. The names of the vector become the category labels, and
ylim leaves room above the tallest bar for the value labels. A
bar chart starts at zero by design, because the length of the bar is what
encodes the value; a truncated axis would exaggerate differences.
$ Rscript bar-chart.R
[,1]
[1,] 0.7
[2,] 1.9
[3,] 3.1
math art music
12 9 7
Pie charts
pie divides a circle into slices proportional to the values. The
function returns nothing useful, because the slices are drawn rather than
positioned on a coordinate system. It is included here because it belongs to
the base graphics system, not because it is the best way to show proportions.
counts <- c(math = 12, art = 9, music = 7)
png("pie.png", width = 600, height = 400)
pie(counts, col = c("steelblue", "lightgreen", "lavender"),
main = "Students per subject")
invisible(dev.off())
print(counts)
cat("total:", sum(counts), "\n")
The three slices represent 12, 9, and 7 students out of 28. A bar chart would make the differences easier to compare, because people judge lengths more accurately than angles. The colours are matched to the slices by position, and the names of the vector supply the labels.
$ Rscript pie-chart.R math art music 12 9 7 total: 28
Several plots on one page
par sets graphical parameters for the current device.
par(mfrow = c(1, 2)) splits the page into one row and two columns,
so the next two plots appear side by side. The same function controls margins,
text size, colours, and the axis style.
x <- 1:20
png("layout.png", width = 700, height = 350)
par(mfrow = c(1, 2))
plot(x, x^2, type = "l", main = "Square", xlab = "x", ylab = "x^2")
plot(x, log(x), type = "l", main = "Logarithm", xlab = "x", ylab = "log(x)")
print(par("mfrow"))
invisible(dev.off())
The printout confirms the layout as one row and two columns. The square grows
quickly and the logarithm grows slowly, and placing the two curves side by
side makes the difference obvious. Parameters set with par stay
in effect until they are changed or the device is closed, so a function that
changes them should restore the old values.
par(mfrow = c(1, 2)).$ Rscript plot-grid.R [1] 1 2
A complete example
The next script annotates a scatter plot. It draws the points, adds a dashed line at the mean score, writes the score next to every point, and adds a legend that explains the two elements. The result is a single self-contained figure suitable for a report.
hours <- c(2, 3, 5, 6, 8, 9, 11, 12)
scores <- c(55, 62, 68, 74, 79, 85, 88, 94)
png("report.png", width = 600, height = 400)
plot(hours, scores, pch = 19, col = "steelblue", ylim = c(50, 100),
main = "Study time and score", xlab = "Hours", ylab = "Score")
abline(h = mean(scores), lty = 2, col = "firebrick")
text(hours, scores, labels = scores, pos = 3, cex = 0.7)
legend("bottomright", legend = c("student", "mean score"),
pch = c(19, NA), lty = c(NA, 2),
col = c("steelblue", "firebrick"))
invisible(dev.off())
cat("mean score:", mean(scores), "\n")
The mean score is 75.625, and the dashed line crosses the vertical axis at
that value. The labels use pos = 3 to sit above each point, and
cex = 0.7 shrinks them so that they do not collide. The legend in
the bottom right names the points and the mean line, which is the minimum
needed for a figure that is read without the surrounding text.
$ Rscript report.R mean score: 75.625
Next steps
The descriptive statistics article computes the numbers that these plots display, and the probability distributions article explains the normal curve behind the histogram. The vectors article covers the data structures that the plotting functions accept. The ggplot2 article later in the series builds the same charts from layers and separates the data from the display.
Source
An Introduction to R: graphics
In this article we have drawn a scatter plot with plot, a line
chart with type = "l", and added points, lines, and a mean with
points and abline. We built a histogram, a boxplot,
a bar chart, and a pie chart, and read the values that the functions returned.
We arranged two panels with par(mfrow) and finished with an
annotated figure that combined a mean line, point labels, and a legend. The
series continues with R ggplot2, which rebuilds
these charts from layers and separates the data from the display.
Author
List all R Language tutorials.