Chapter 2 Companion Script: Graphical Summaries
This page accompanies a single, self-contained R script that reproduces every kind of graph in Chapter 2—frequency tables, pie charts, bar graphs, histograms, and density/normal overlays—using the same conventions you are expected to follow on the computer assignments.
Download stat350_ch02_graphical_summaries.R
How to use the script
Set up R and RStudio first if you have not already: see Getting Started with R and RStudio.
Open the script in RStudio and run it top to bottom once. Part 0 loads ggplot2 (the only package required), sets a course-wide theme, and defines the bin-rule helper; after that, every block is self-contained, so you can re-run any single plot later without restarting.
Blocks marked
[TRAP]are deliberate: they show a common mistake first, then the fix. Run both and compare the plots—these are the mistakes that actually cost points on assignments.
How the script maps onto the webbook
Part |
Topic |
Webbook section |
|---|---|---|
Part 0 |
Setup: ggplot2, a course-wide |
— |
Part 1 |
The structure of a data set (aggregated vs. raw data, |
2.1 |
Part 2 |
Frequency tables (counts, relative frequencies, percentages) |
2.2 |
Part 3 |
Pie charts (and why |
2.2 |
Part 4 |
Bar graphs: simple, dodged, stacked; three |
2.2 |
Part 5 |
Bar graph or histogram? A |
2.3 |
Part 6 |
Histograms and the bin rule of thumb |
2.3 |
Part 7 |
Density and normal overlays (the course histogram recipe) |
2.3 |
Part 8 |
Shape: modality, skewness, and outliers; faceting |
2.4 |
Six practice exercises at the end of the script modify specific parts and ask you to explain what changes and why.
Two conventions worth knowing
The bin rule, written once. The script encodes the Chapter 2.3 rule of thumb \(b = \max(\text{round}(\sqrt{n}) + 2,\ 5)\) as a function, so the formula in your code visibly matches the formula in the webbook:
n_bins <- function(n) {
max(round(sqrt(n)) + 2, 5)
}
n_bins(72) # InsectSprays -> 10
n_bins(90) # furnace -> 11
n_bins(100) # -> 12
The course histogram recipe. From Part 7 on, every single-variable histogram carries a density scale, a red kernel density curve, and a blue normal curve—the same layering required on the computer assignments:
ggplot(furnace, aes(x = Consumption)) +
geom_histogram(aes(y = after_stat(density)),
bins = bins, fill = "purple", colour = "black",
linewidth = 0.6) +
geom_density(colour = "red", linewidth = 1.5) +
stat_function(fun = dnorm, args = list(mean = xbar, sd = s),
colour = "blue", linewidth = 1.5) +
coord_cartesian(xlim = c(0, 20)) +
labs(title = "Residential furnace energy consumption",
x = "BTU", y = "Density")
For a deeper treatment of the plotting layers used throughout the script, see Graphics (ggplot2); for the datasets it loads, see Course Datasets.