Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 39 ยท Visualization

Base R Graphics: plot, hist, barplot, boxplot and par

Draw charts with base R: plot, lines, points, hist, barplot, boxplot, pie, colors, legends, multi-panel layouts with par, and saving figures to PNG or PDF.

R was built for statistics, and drawing pictures of data is part of the toolkit from the first install. The base graphics system needs no packages: you call plot(), hist() or barplot() and a chart appears in the plotting window. It is quick for exploring data and for a quick check of a result. The next lessons introduce ggplot2, which is better for polished, layered figures, but base graphics remain everywhere in R code and documentation.

This site cannot run R, so the code below is read-only and the charts are described, not shown. Paste the code into R or RStudio to see them. The built-in data sets mtcars, iris and faithful are always available, so nothing needs to be downloaded.

How base graphics work: the painter's model

Base graphics paint onto a canvas. A high-level function (plot, hist, barplot, boxplot) starts a new plot. Low-level functions (lines, points, abline, text, legend, title, axis) add to the existing plot. Once something is painted you cannot edit it; to change anything, you re-run the code. That is the main difference to the layered object model of ggplot2.

Scatter plots with plot()

R
plot(mtcars$wt, mtcars$mpg,
     main = "Fuel economy versus weight",
     xlab = "Weight (1000 lbs)", ylab = "Miles per gallon",
     pch = 19, col = "steelblue")

The result: 32 dots with weight on the x-axis and miles per gallon on the y-axis; heavier cars sit lower, so the cloud slopes down. pch chooses the point symbol (19 is a solid circle), col the color, cex the size.

Add a fitted line and a reference line on top:

R
abline(lm(mpg ~ wt, data = mtcars), col = "red", lwd = 2)   # regression line
abline(h = mean(mtcars$mpg), lty = 2)                        # dashed horizontal line

You can also use the formula interface, which reads like a sentence ("mpg as a function of wt"): plot(mpg ~ wt, data = mtcars).

The type argument changes what plot() draws: "p" points (default), "l" lines, "b" both, "h" vertical bars, "s" steps.

R
x <- seq(0, 2 * pi, length.out = 100)
plot(x, sin(x), type = "l", col = "darkgreen", lwd = 2)
lines(x, cos(x), col = "orange", lwd = 2)
legend("topright", legend = c("sin", "cos"),
       col = c("darkgreen", "orange"), lwd = 2)

This draws two smooth waves; legend() places a key in the corner.

Histograms

A histogram shows how a numeric variable is distributed by counting values in bins.

R
hist(mtcars$mpg, main = "Distribution of mpg", xlab = "mpg", col = "lightgray")

By default R chooses the number of bins with Sturges' rule. You can look at the numbers behind the picture without drawing it:

R
h <- hist(mtcars$mpg, plot = FALSE)
h$breaks    # 10 15 20 25 30 35
h$counts    #  6 12  8  2  4

Each bin is right-closed by default, (10, 15], so a value of exactly 15 falls in the first bin. Use breaks = 10 to ask for about ten bins, or a vector of your own cut points. hist(x, freq = FALSE) plots densities instead of counts, so that you can overlay lines(density(x)).

Bar charts

barplot() draws bars from heights, so you usually summarize the data first. table() counts categories:

R
counts <- table(mtcars$cyl)
counts
#
#  4  6  8 
# 11  7 14 
barplot(counts, main = "Cars by cylinders", xlab = "Cylinders", ylab = "Count",
        col = c("tomato", "gold", "skyblue"))

For means per group, compute them first with tapply() and plot the result: barplot(tapply(mtcars$mpg, mtcars$cyl, mean)). Use beside = TRUE with a two-way table to get side-by-side bars instead of stacks, and horiz = TRUE for horizontal bars (handy for long labels).

Box plots

A box plot summarizes a distribution in five numbers (minimum, first quartile, median, third quartile, maximum) and marks outliers as separate dots. The formula interface compares groups at once:

R
boxplot(mpg ~ cyl, data = mtcars,
        main = "mpg by number of cylinders",
        xlab = "Cylinders", ylab = "mpg",
        col = "lightblue")

You see three boxes. The 4-cylinder box sits highest and the 8-cylinder box lowest, and the median line in each box is the group median. The whiskers extend to the most extreme points within 1.5 times the interquartile range of the box; dots beyond that are outliers. boxplot.stats(x)$out lists them without drawing anything.

Other chart types

R
pie(c(40, 35, 25), labels = c("A", "B", "C"))     # pie charts: use sparingly
plot(density(mtcars$mpg))                          # smooth distribution curve
pairs(mtcars[, c("mpg", "wt", "hp")])              # matrix of scatter plots
matplot(1:5, cbind(1:5, (1:5)^2), type = "b")      # several columns at once
curve(x^2, from = -2, to = 2)                      # plot a function

pairs() is a fast first look at how several variables relate. curve() is handy for mathematics lessons because you pass a plain expression in x.

Colors, symbols and line types

Argument Meaning Typical values
col color "red", "#1f77b4", rgb(0.2, 0.4, 0.8), 1:8
pch point symbol 1 open circle, 16/19 solid circle, 17 triangle
lty line type 1 solid, 2 dashed, 3 dotted
lwd line width 1, 2, 3
cex size multiplier 0.8, 1.5

Colors can be colored by group with a factor index: plot(iris$Sepal.Length, iris$Petal.Length, col = iris$Species, pch = 19) draws the three species in three colors (the default palette). colors() lists the 657 built-in names, and palette() shows the default ordering.

Several plots on one page: par()

par() sets global graphics options. mfrow = c(rows, cols) splits the window into a grid. Save the old settings and restore them, so one script does not leave its layout behind:

R
old <- par(mfrow = c(1, 2), mar = c(4, 4, 2, 1))
hist(mtcars$mpg, main = "mpg")
boxplot(mtcars$mpg, main = "mpg")
par(old)

mar is the margin around each plot in lines (bottom, left, top, right). If R complains "figure margins too large", the window is too small for the layout.

Saving a figure

Open a graphics device (a file), draw, then close it with dev.off():

R
png("mpg-vs-weight.png", width = 800, height = 600, res = 120)
plot(mpg ~ wt, data = mtcars, pch = 19)
dev.off()

Use pdf("file.pdf", width = 7, height = 5) for vector output that stays sharp in documents, and svg() for the web. Forgetting dev.off() leaves the file empty or unfinished, a very common beginner mistake.

A runnable stand-in (Python)

You cannot draw plots here, but you can check the numbers behind a histogram and box plot. This Python block reproduces hist()'s default bins for mpg and the box-plot outlier rule for hp. It is a comparison, not R.

Python Python comparison: the numbers behind hist() and boxplot()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Common mistakes

  • Calling lines() or points() with no plot open: "plot.new has not been called yet".
  • Forgetting dev.off() after png().
  • Plotting a data frame column that is a factor or character where you meant numbers.
  • Using barplot() on raw data instead of on counts or means.
  • Leaving par(mfrow = ...) set, so later plots land in tiny panels. Restore it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the difference between plot() and lines()?

    High-level functions start a new plot; low-level functions such as lines(), points() and abline() paint onto the current plot.
  2. 2. Which call draws one box per group of cyl?

    The formula y ~ group splits the numeric variable y by the grouping variable and draws a box for each group.
  3. 3. What must you do after png('plot.png') and the plotting commands?

    dev.off() closes the graphics device and finishes writing the file.
  4. 4. What does par(mfrow = c(2, 3)) do?

    mfrow = c(rows, columns) divides the device into a grid that is filled row by row.

Summary

  • High-level functions start a plot; low-level functions (lines, points, abline, legend) add to it.
  • plot(), hist(), barplot(), boxplot() cover scatter, distribution, count and group-comparison charts.
  • col, pch, lty, lwd and cex control appearance; par(mfrow = ...) makes panels.
  • png()/pdf() ... dev.off() saves a figure.
  • Base graphics are fast and dependency-free; ggplot2 is better for layered, polished work.

Next: ggplot2 Basics