Graphics with Base R: boxplots, histograms and a Saved PNG
Draw a boxplot, a histogram, a bar chart with error bars and a scatter plot with a regression line in base R, save them to a PNG file, and verify the numbers behind each plot and the file itself.
In this lesson you will
- Draw the four basic plots
- Save a plot to a PNG file
- Get the numbers behind a plot
- Check the file and the numbers
About 28 minutes
Showing the result to the class
A table of means convinces a statistician, and a picture convinces everybody else. Base R can draw plots with no packages: boxplot shows the median, the quartiles and the extremes of each group, hist shows how a variable is distributed, barplot shows one number per category, and plot draws a scatter plot, to which abline adds a line, such as the regression line from lesson 9. Each of these opens a graphics device, a place to draw. By default that is a window on the screen, and in a script you choose a file device such as png(), draw, and close the device with dev.off(), which writes the file.
A picture cannot be checked by reading its numbers, and a plot can be wrong without any error message, so this lesson checks two things. First, the file: a PNG starts with an eight-byte signature, and its header states the width and height in pixels, which the script reads with readBin and compares with what it asked for. Second, the numbers: every plotting function can return the statistics that it computes when you call it with plot = FALSE. For a boxplot these are the five numbers of each group, and for a histogram the breaks and the counts, which Python can recompute independently. Use clear colours that are easy to tell apart, label the axes with units, and give each plot a title that states the finding.
| Plot | Function | What to check |
|---|---|---|
| Distribution by group | boxplot(y ~ g) | Medians, quartiles, outliers |
| Distribution of one variable | hist(x) | Breaks and counts |
| One value per category | barplot(m) | Heights match the table |
| Relationship | plot(x, y); abline(fit) | Line matches lm |
| Save | png(f); …; dev.off() | Close the device |
height <- c(12.1, 13.4, 11.8, 12.9, 15.2, 16.8, 14.9, 15.7, 18.3, 17.5, 19.1, 18.8)
leaves <- c(6, 7, 6, 7, 8, 9, 8, 8, 10, 9, 11, 10)
group <- factor(rep(c("control", "organic", "chemical"), each = 4), levels = c("control", "organic", "chemical"))
f <- tempfile(fileext = ".png")
png(f, width = 1000, height = 800)
par(mfrow = c(2, 2))
bp <- boxplot(height ~ group, ylab = "Height (cm)", main = "Height by group", col = c("grey80", "lightgreen", "lightblue"))
hs <- hist(height, breaks = c(10, 12, 14, 16, 18, 20), main = "Distribution of heights", xlab = "Height (cm)", col = "steelblue")
means <- tapply(height, group, mean)
sds <- tapply(height, group, sd)
mids <- barplot(means, ylim = c(0, 22), ylab = "Mean height (cm)", main = "Mean and standard deviation", col = "seagreen")
arrows(mids, means - sds, mids, means + sds, angle = 90, code = 3, length = 0.05)
fit <- lm(height ~ leaves)
plot(leaves, height, pch = 19, xlab = "Leaves", ylab = "Height (cm)", main = "Height against leaves")
abline(fit, lty = 2)
invisible(dev.off())
hdr <- readBin(f, "raw", 24)
cat("PNG signature:", paste(sprintf("%02x", as.integer(hdr[1:8])), collapse = " "), "\n")
cat("header says width", sum(as.integer(hdr[17:20]) * 256^(3:0)), "and height", sum(as.integer(hdr[21:24]) * 256^(3:0)), "\n")
cat("file has content:", file.size(f) > 5000, "| device closed:", dev.cur() == 1, "\n")
cat("boxplot stats:\n")
print(bp$stats)
cat("histogram breaks:", hs$breaks, "| counts:", hs$counts, "\n")
cat("bar heights:", round(mids, 1), "->", round(means, 3), "| error bar ends of control:", round(means[1] - sds[1], 3), round(means[1] + sds[1], 3), "\n")
cat("line drawn: intercept", round(coef(fit)[1], 4), "slope", round(coef(fit)[2], 4), "\n")
unlink(f)
PNG signature: 89 50 4e 47 0d 0a 1a 0a
header says width 1000 and height 800
file has content: TRUE | device closed: TRUE
boxplot stats:
[,1] [,2] [,3]
[1,] 11.80 14.90 17.50
[2,] 11.95 15.05 17.90
[3,] 12.50 15.45 18.55
[4,] 13.15 16.25 18.95
[5,] 13.40 16.80 19.10
histogram breaks: 10 12 14 16 18 20 | counts: 1 3 3 2 3
bar heights: 0.7 1.9 3.1 -> 12.55 15.65 18.425 | error bar ends of control: 11.817 13.283
line drawn: intercept 2.3782 slope 1.5956
The script drew all four plots on one 1000 by 800 pixel canvas, divided into a grid of 2 by 2 panels by par(mfrow = c(2, 2)), and closed the device. The PNG file starts with the signature 89 50 4e 47 0d 0a 1a 0a, which every PNG file has (the bytes spell “PNG”), and the header, read back from the file, says that the image is 1000 pixels wide and 800 high, exactly what was requested. The file is not empty (TRUE), and the device is closed (TRUE): forgetting dev.off() is the most common reason for a PNG that is empty or damaged.
To verify the contents, the functions were asked for their numbers. The boxplot statistics are a matrix with one column for each group and five rows: the lower whisker, the lower hinge, the median, the upper hinge and the upper whisker:
11.8 14.9 17.5
11.95 15.05 17.9
12.5 15.45 18.55
13.15 16.25 18.95
13.4 16.8 19.1
Columns are control, organic and chemical. For the control group the median is 12.50, between the middle two of 11.8, 12.1, 12.9 and 13.4, the hinges are the medians of each half, and with four values and no outliers the whiskers reach the extremes. The histogram with the breaks 10 12 14 16 18 20 counted 1 3 3 2 3 plants in the five classes, where each class includes its upper end, so a height of exactly 14 would fall in the class from 12 to 14. The bar chart drew bars of the mean heights, and the error bars of the control group run from 11.817 to 13.283, one standard deviation each way. The line in the scatter plot has intercept 2.3782 and slope 1.5956, as in lesson 9.
Independent check: Python computed the five numbers of each group with Tukey’s method, the same one fivenum uses, counted the histogram classes by hand with the right-closed rule, and fitted the line with numpy. All of them match. That means that what the plots show is what the data say, and the check cost a few lines of code.
Check by hand for the control group: sorted, the heights are 11.8, 12.1, 12.9 and 13.4. The median is (12.1 + 12.9) / 2 = 12.5, the lower hinge is the median of the lower half, (11.8 + 12.1) / 2 = 11.95, and the upper hinge is (12.9 + 13.4) / 2 = 13.15. The five heights in the class from 14 to 16 are 14.9, 15.2 and 15.7, three plants, and the class from 16 to 18 has 16.8 and 17.5.
If you forget dev.off(), the file may be empty and the next plot may draw on top of the old device. Use invisible(dev.off()) to avoid printing the “null device” message.
Use clearly different light and dark colours rather than reds against greens, and never rely on colour alone: add labels, shapes or line types, as the dashed line does here.
Every program in this lesson was run with R 4.3.3 using Rscript –vanilla (base R only, no packages) while the course was written. R releases new versions every year, so check r-project.org for the current version and for any change in behaviour. The image was drawn to a temporary file and deleted. The plot itself is not shown in this text, and you can run the script to see it. The png device needs graphics support in your R build.
Practice
Save the same plots as a PDF with pdf(file, width = 7, height = 5) and compare the sizes. Add a legend with legend() to the scatter plot. Make a boxplot of growth, week 4 minus week 1, per group and check the median with Python.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What does dev.off() do?
- Deletes the plot
- Closes the device and writes the file
- Opens a window
- Sorts the data
Forgetting it can leave an empty file.
How can you get the numbers behind a boxplot?
- Call boxplot with plot = FALSE, or keep its return value
- Take a screenshot
- Use summary only
- You cannot
It returns stats, n and more.
What does par(mfrow = c(2, 2)) do?
- Splits the canvas into a 2 by 2 grid
- Sets the colours
- Closes the device
- Saves the file
Four plots on one canvas.
Why read the PNG header?
- To compress it
- To edit it
- To print it
- To check that the file really is the requested size
The header holds width and height.
Which classes does hist include at the upper end?
- The left end only
- Neither
- Both
- By default the right end is included
right = TRUE is the default.
Summary
- Open a device, draw, then close it with dev.off().
- boxplot, hist, barplot and plot cover the basic charts; abline adds a line.
- Ask plotting functions for their numbers and check them.
- Verify the saved file by reading its header.
Questions
Is base R graphics enough?
For many reports, yes. The ggplot2 package is popular for more elaborate graphics, and it has a different grammar. Check its documentation if you need it.
How do I save a plot at higher resolution?
Increase width and height in pixels, or set res = 150 or more, in png(). For print, a vector format such as pdf or svg scales without losing quality.
Why does my plot not appear when running Rscript?
Rscript has no screen window, so graphics go to a file called Rplots.pdf unless you open a device such as png() yourself.
