.. _r_ch02_graphical_summaries: 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:`Download stat350_ch02_graphical_summaries.R ` **How to use the script** 1. Set up R and RStudio first if you have not already: see :ref:`r_setup_guide`. 2. 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. 3. 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** .. list-table:: :header-rows: 1 :widths: 12 63 25 * - Part - Topic - Webbook section * - Part 0 - Setup: ggplot2, a course-wide ``theme_set()``, and the bin rule as a function - — * - Part 1 - The structure of a data set (aggregated vs. raw data, ``geom_bar`` vs. ``geom_col``) - 2.1 * - Part 2 - Frequency tables (counts, relative frequencies, percentages) - 2.2 * - Part 3 - Pie charts (and why ``theme_void()`` is mandatory) - 2.2 * - Part 4 - Bar graphs: simple, dodged, stacked; three ``[TRAP]`` blocks - 2.2 * - Part 5 - Bar graph or histogram? A ``[TRAP]`` where ``table()`` destroys the number line - 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 :math:`b = \max(\text{round}(\sqrt{n}) + 2,\ 5)` as a function, so the formula in your code visibly matches the formula in the webbook: .. literalinclude:: RCodes/stat350_ch02_graphical_summaries.R :language: r :start-at: n_bins <- function :end-at: n_bins(100) **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: .. literalinclude:: RCodes/stat350_ch02_graphical_summaries.R :language: r :start-at: ggplot(furnace, aes(x = Consumption)) + :end-at: x = "BTU", y = "Density") For a deeper treatment of the plotting layers used throughout the script, see :ref:`r_ggplot2_guide`; for the datasets it loads, see :ref:`r_datasets`.