In this lab, you’ll investigate the probability distribution that is most central to statistics: the normal distribution. If you are confident that your data are nearly normal, that opens the door to many powerful statistical methods. Here we’ll use the graphical tools of R to assess the normality of our data and also learn how to generate random numbers from a normal distribution.

Getting Started

Load packages

In this lab, we will explore and visualize the data using the tidyverse suite of packages as well as the openintro package.

Let’s load the packages.

# Load required packages
library(tidyverse)
library(openintro)

The data

This week you’ll be working with fast food data. This data set contains data on 515 menu items from some of the most popular fast food restaurants worldwide. Let’s take a quick peek at the first few rows of the data.

Either you can use glimpse like before, or head to do this.

# Load the dataset from the openintro package
data("fastfood", package = "openintro")

# Display the first few rows
head(fastfood)
## # A tibble: 6 × 17
##   restaurant item       calories cal_fat total_fat sat_fat trans_fat cholesterol
##   <chr>      <chr>         <dbl>   <dbl>     <dbl>   <dbl>     <dbl>       <dbl>
## 1 Mcdonalds  Artisan G…      380      60         7       2       0            95
## 2 Mcdonalds  Single Ba…      840     410        45      17       1.5         130
## 3 Mcdonalds  Double Ba…     1130     600        67      27       3           220
## 4 Mcdonalds  Grilled B…      750     280        31      10       0.5         155
## 5 Mcdonalds  Crispy Ba…      920     410        45      12       0.5         120
## 6 Mcdonalds  Big Mac         540     250        28      10       1            80
## # ℹ 9 more variables: sodium <dbl>, total_carb <dbl>, fiber <dbl>, sugar <dbl>,
## #   protein <dbl>, vit_a <dbl>, vit_c <dbl>, calcium <dbl>, salad <chr>

You’ll see that for every observation there are 17 measurements, many of which are nutritional facts.

You’ll be focusing on just three columns to get started: restaurant, calories, calories from fat.

Let’s first focus on just products from McDonalds and Dairy Queen.

mcdonalds <- fastfood %>%
  filter(restaurant == "Mcdonalds")

dairy_queen <- fastfood %>%
  filter(restaurant == "Dairy Queen")
  1. Make a plot (or plots) to visualize the distributions of the amount of calories from fat of the options from these two restaurants. How do their centers, shapes, and spreads compare?
# Combine the two restaurants and plot their calorie-from-fat distributions
fat <- bind_rows(
  mcdonalds %>% transmute(restaurant = "Mcdonalds", cal_fat),
  dairy_queen %>% transmute(restaurant = "Dairy Queen", cal_fat)
) %>% drop_na(cal_fat)

ggplot(fat, aes(x = cal_fat, fill = restaurant)) +
  geom_density(alpha = 0.4, adjust = 1.1) +
  labs(
    title = "Calories from Fat: McDonald's vs Dairy Queen",
    x = "Calories from Fat",
    y = "Density",
    fill = "Restaurant"
  )

The plot shows that Dairy Queen items have higher calories from fat on average, with a broader spread and a right-skewed shape. McDonald’s items are generally lower in fat calories and more tightly clustered.

The normal distribution

In your description of the distributions, did you use words like bell-shapedor normal? It’s tempting to say so when faced with a unimodal symmetric distribution.

To see how accurate that description is, you can plot a normal distribution curve on top of a histogram to see how closely the data follow a normal distribution. This normal curve should have the same mean and standard deviation as the data. You’ll be focusing on calories from fat from Dairy Queen products, so let’s store them as a separate object and then calculate some statistics that will be referenced later.

dqmean <- mean(dairy_queen$cal_fat)
dqsd   <- sd(dairy_queen$cal_fat)

Next, you make a density histogram to use as the backdrop and use the lines function to overlay a normal probability curve. The difference between a frequency histogram and a density histogram is that while in a frequency histogram the heights of the bars add up to the total number of observations, in a density histogram the areas of the bars add up to 1. The area of each bar can be calculated as simply the height times the width of the bar. Using a density histogram allows us to properly overlay a normal distribution curve over the histogram since the curve is a normal probability density function that also has area under the curve of 1. Frequency and density histograms both display the same exact shape; they only differ in their y-axis. You can verify this by comparing the frequency histogram you constructed earlier and the density histogram created by the commands below.

ggplot(data = dairy_queen, aes(x = cal_fat)) +
        geom_blank() +
        geom_histogram(aes(y = ..density..)) +
        stat_function(fun = dnorm, args = c(mean = dqmean, sd = dqsd), col = "tomato")

After initializing a blank plot with geom_blank(), the ggplot2 package (within the tidyverse) allows us to add additional layers. The first layer is a density histogram. The second layer is a statistical function – the density of the normal curve, dnorm. We specify that we want the curve to have the same mean and standard deviation as the column of fat calories. The argument col simply sets the color for the line to be drawn. If we left it out, the line would be drawn in black.

  1. Based on the this plot, does it appear that the data follow a nearly normal distribution?
# Plot a density histogram with an overlaid normal curve
dqmean <- mean(dairy_queen$cal_fat)
dqsd   <- sd(dairy_queen$cal_fat)

ggplot(data = dairy_queen, aes(x = cal_fat)) +
  geom_histogram(aes(y = ..density..),
                 bins = 20, fill = "lightblue", color = "black") +
  stat_function(fun = dnorm,
                args = list(mean = dqmean, sd = dqsd),
                color = "tomato", linewidth = 1) +
  labs(
    title = "Calories from Fat — Dairy Queen",
    x = "Calories from Fat",
    y = "Density"
  )

The histogram shows a roughly bell-shaped distribution with a slight right skew (a longer tail for higher-fat items). The normal curve fits most of the data fairly well, but not perfectly — the extreme values suggest that while the data are approximately normal, they’re not perfectly symmetric.

Evaluating the normal distribution

Eyeballing the shape of the histogram is one way to determine if the data appear to be nearly normally distributed, but it can be frustrating to decide just how close the histogram is to the curve. An alternative approach involves constructing a normal probability plot, also called a normal Q-Q plot for “quantile-quantile”.

ggplot(data = dairy_queen, aes(sample = cal_fat)) + 
  geom_line(stat = "qq")

This time, you can use the geom_line() layer, while specifying that you will be creating a Q-Q plot with the stat argument. It’s important to note that here, instead of using x instead aes(), you need to use sample.

The x-axis values correspond to the quantiles of a theoretically normal curve with mean 0 and standard deviation 1 (i.e., the standard normal distribution). The y-axis values correspond to the quantiles of the original unstandardized sample data. However, even if we were to standardize the sample data values, the Q-Q plot would look identical. A data set that is nearly normal will result in a probability plot where the points closely follow a diagonal line. Any deviations from normality leads to deviations of these points from that line.

The plot for Dairy Queen’s calories from fat shows points that tend to follow the line but with some errant points towards the upper tail. You’re left with the same problem that we encountered with the histogram above: how close is close enough?

A useful way to address this question is to rephrase it as: what do probability plots look like for data that I know came from a normal distribution? We can answer this by simulating data from a normal distribution using rnorm.

sim_norm <- rnorm(n = nrow(dairy_queen), mean = dqmean, sd = dqsd)

The first argument indicates how many numbers you’d like to generate, which we specify to be the same number of menu items in the dairy_queen data set using the nrow() function. The last two arguments determine the mean and standard deviation of the normal distribution from which the simulated sample will be generated. You can take a look at the shape of our simulated data set, sim_norm, as well as its normal probability plot.

  1. Make a normal probability plot of sim_norm. Do all of the points fall on the line? How does this plot compare to the probability plot for the real data? (Since sim_norm is not a data frame, it can be put directly into the sample argument and the data argument can be dropped.)
# Create a normal probability (Q-Q) plot for the simulated normal data
ggplot(mapping = aes(sample = sim_norm)) +
  geom_qq(color = "steelblue") +
  geom_qq_line(color = "darkred") +
  labs(
    title = "Normal Q-Q Plot of Simulated Normal Data",
    x = "Theoretical Quantiles",
    y = "Sample Quantiles"
  )

All the points in the simulated normal data fall closely along the diagonal line, which is expected since the data were generated from a normal distribution. This plot confirms what a perfectly normal dataset looks like, providing a strong visual baseline for comparing to the Dairy Queen data.

Even better than comparing the original plot to a single plot generated from a normal distribution is to compare it to many more plots using the following function. It shows the Q-Q plot corresponding to the original data in the top left corner, and the Q-Q plots of 8 different simulated normal data. It may be helpful to click the zoom button in the plot window.

# Compare Q-Q plot for Dairy Queen data with 8 simulated normal datasets
qqnormsim(sample = cal_fat, data = dairy_queen)

  1. Does the normal probability plot for the calories from fat look similar to the plots created for the simulated data? That is, do the plots provide evidence that the calories are nearly normal?

**The Q-Q plot for Dairy Queen’s calories from fat looks similar to the simulated normal plots in the middle portion, where most points fall along the diagonal line. However, the upper tail shows a few points that deviate upward, indicating some high-fat menu items that are not perfectly normal.

Overall, the data appear roughly normal, with slight right-tail skewness. This suggests the calories from fat follow a distribution that is close to normal but not perfectly so.**

  1. Using the same technique, determine whether or not the calories from McDonald’s menu appear to come from a normal distribution.
# Calculate mean and standard deviation for McDonald's calories from fat
mc_mean <- mean(mcdonalds$cal_fat, na.rm = TRUE)
mc_sd   <- sd(mcdonalds$cal_fat, na.rm = TRUE)

# Compare McDonald's data Q-Q plot to simulated normal datasets
qqnormsim(sample = cal_fat, data = mcdonalds)

The Q-Q plot for McDonald’s calories from fat shows more noticeable deviations from the diagonal line compared to Dairy Queen. The points curve upward in the upper tail and downward in the lower tail, suggesting the data are right-skewed. This means McDonald’s menu items’ calories from fat do not follow a perfectly normal distribution, though the central portion appears somewhat close.

Normal probabilities

Okay, so now you have a slew of tools to judge whether or not a variable is normally distributed. Why should you care?

It turns out that statisticians know a lot about the normal distribution. Once you decide that a random variable is approximately normal, you can answer all sorts of questions about that variable related to probability. Take, for example, the question of, “What is the probability that a randomly chosen Dairy Queen product has more than 600 calories from fat?”

If we assume that the calories from fat from Dairy Queen’s menu are normally distributed (a very close approximation is also okay), we can find this probability by calculating a Z score and consulting a Z table (also called a normal probability table). In R, this is done in one step with the function pnorm().

# Theoretical probability (normal curve)
1 - pnorm(q = 600, mean = dqmean, sd = dqsd)
## [1] 0.01501523

Note that the function pnorm() gives the area under the normal curve below a given value, q, with a given mean and standard deviation. Since we’re interested in the probability that a Dairy Queen item has more than 600 calories from fat, we have to take one minus that probability.

Assuming a normal distribution has allowed us to calculate a theoretical probability. If we want to calculate the probability empirically, we simply need to determine how many observations fall above 600 then divide this number by the total sample size.

# Empirical probability (based on real data)
dairy_queen %>%
  filter(cal_fat > 600) %>%
  summarise(percent = n() / nrow(dairy_queen))
## # A tibble: 1 × 1
##   percent
##     <dbl>
## 1  0.0476

Although the probabilities are not exactly the same, they are reasonably close. The closer that your distribution is to being normal, the more accurate the theoretical probabilities will be.

  1. Write out two probability questions that you would like to answer about any of the restaurants in this dataset. Calculate those probabilities using both the theoretical normal distribution as well as the empirical distribution (four probabilities in all). Which one had a closer agreement between the two methods?
# Theoretical (assume normal with mean = dqmean, sd = dqsd)
p_theo_dq_300_500 <- pnorm(500, mean = dqmean, sd = dqsd) -
                     pnorm(300, mean = dqmean, sd = dqsd)
p_theo_dq_300_500
## [1] 0.3373713
# Empirical (proportion in the actual data)
p_emp_dq_300_500 <- dairy_queen %>%
  summarize(prop = mean(cal_fat >= 300 & cal_fat <= 500, na.rm = TRUE))
p_emp_dq_300_500
## # A tibble: 1 × 1
##    prop
##   <dbl>
## 1 0.262
# Mean/SD for McDonald's cal_fat (in case not computed above)
mc_mean <- mean(mcdonalds$cal_fat, na.rm = TRUE)
mc_sd   <- sd(mcdonalds$cal_fat, na.rm = TRUE)
mc_mean; mc_sd
## [1] 285.614
## [1] 220.8993
# Theoretical (assume normal for McDonald's cal_fat)
p_theo_mcd_gt400 <- 1 - pnorm(400, mean = mc_mean, sd = mc_sd)
p_theo_mcd_gt400
## [1] 0.3022921
# Empirical (proportion in the actual data)
p_emp_mcd_gt400 <- mcdonalds %>%
  summarize(prop = mean(cal_fat > 400, na.rm = TRUE))
p_emp_mcd_gt400
## # A tibble: 1 × 1
##    prop
##   <dbl>
## 1 0.158

**For Dairy Queen, the theoretical probability 𝑃 ( 300 ≤ cal_fat ≤ 500 ) P(300≤cal_fat≤500) was close to the empirical proportion from the data, indicating good agreement—consistent with our earlier finding that DQ’s cal_fat is roughly normal.

For McDonald’s, the theoretical probability 𝑃 ( cal_fat > 400 ) P(cal_fat>400) differed more from the empirical proportion, reflecting the right-skew we saw in McDonald’s distribution.

Conclusion: The Dairy Queen question showed closer agreement between theoretical (normal) and empirical probabilities than the McDonald’s question, because the normality assumption fits DQ better than McDonald’s.**


More Practice

  1. Now let’s consider some of the other variables in the dataset. Out of all the different restaurants, which ones’ distribution is the closest to normal for sodium?
# Create normal Q-Q plots for sodium by restaurant
fastfood %>%
  ggplot(aes(sample = sodium)) +
  stat_qq() +
  stat_qq_line() +
  facet_wrap(~ restaurant, scales = "free") +
  labs(
    title = "Normal Q-Q Plots of Sodium by Restaurant",
    x = "Theoretical Quantiles (Normal)",
    y = "Sample Quantiles"
  )

Based on the Q-Q plots, Subway and Dairy Queen appear to have sodium distributions that are closest to normal — their points align more tightly along the diagonal compared to other restaurants. In contrast, restaurants like McDonald’s and Burger King show clear deviations, especially in the upper tails, indicating right-skewed sodium distributions with several high-sodium outliers.

  1. Note that some of the normal probability plots for sodium distributions seem to have a stepwise pattern. why do you think this might be the case?

**The stepwise pattern in the normal probability (Q-Q) plots occurs because the sodium values are rounded or recorded in discrete increments (for example, 10 mg or 50 mg steps).

Since there aren’t many unique sodium values, several menu items share the exact same sodium level, producing flat segments in the plot instead of a smooth curve.

This happens when the data are not truly continuous — even though sodium is numeric, it behaves more like a grouped variable, leading to the “stair-step” appearance in the Q-Q plot.**

  1. As you can see, normal probability plots can be used both to assess normality and visualize skewness. Make a normal probability plot for the total carbohydrates from a restaurant of your choice. Based on this normal probability plot, is this variable left skewed, symmetric, or right skewed? Use a histogram to confirm your findings.
# Normal probability plot (Q-Q) for total carbohydrates - McDonald's
ggplot(mcdonalds, aes(sample = total_carb)) +
  stat_qq() +
  stat_qq_line(color = "blue") +
  labs(
    title = "Normal Q-Q Plot of Total Carbohydrates (McDonald's)",
    x = "Theoretical Quantiles (Normal)",
    y = "Sample Quantiles"
  )

# Histogram for total carbohydrates - McDonald's
ggplot(mcdonalds, aes(x = total_carb)) +
  geom_histogram(binwidth = 10, fill = "lightblue", color = "black") +
  labs(
    title = "Distribution of Total Carbohydrates (McDonald's)",
    x = "Total Carbohydrates (grams)",
    y = "Frequency"
  )

**The Q-Q plot for McDonald’s total carbohydrates shows points curving above the line at the left and below the line at the right, indicating a right-skewed (positively skewed) distribution.

The histogram confirms this — most menu items have moderate carb values, but a few items (like large fries or desserts) have very high carbohydrate counts, creating a long right tail.

Therefore, McDonald’s total carbohydrate data are not normally distributed and show a right-skewed shape due to several high-carb outliers.**