library(tidyverse)
library(openintro)The normal distribution
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.
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.
library(tidyverse)
library(openintro)
data("fastfood", package='openintro')
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")- 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?
fastfood |>
filter(restaurant %in% c("Mcdonalds", "Dairy Queen")) |>
ggplot(aes(x = cal_fat, fill = restaurant)) +
geom_density(alpha = 0.35) When looking at density plots (above), histograms and boxplots (below) that visualize the distributions of the amount of calories from fat of the options for McDonalds and Dairy Queen, we can see that they are both right skewed (tails on the right side of the plot) and are unimodal, with high peaked centers roughly in similar areas of the density plot. Dairy Queen has a higher peak than Mcdonalds, which also has a wider range of distribution (longer right tail). We can see again that the median calories from fat for Mcdonalds is higher than the median calories from fat for dairy queen. It appears that within the IQR Mcdonalds calories from fat exhibits more symmetry about the mean when compared to Dairy Queen.
fastfood |>
filter(restaurant %in% c("Mcdonalds", "Dairy Queen")) |>
ggplot(aes(x = cal_fat, fill = restaurant)) +
geom_histogram(binwidth = 30, position = "dodge") fastfood |>
filter(restaurant %in% c("Mcdonalds", "Dairy Queen")) |>
ggplot(aes(x = cal_fat, y = restaurant)) +
geom_boxplot(position = "dodge") 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(dairy_queen, aes(x = cal_fat)) +
geom_histogram() +
labs( title = "Frequency Histogram - Dairy Queen")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") +
labs(title = "Density Histogram - Dairy Queen")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.
- Based on the this plot, does it appear that the data follow a nearly normal distribution?
It is sort of hard to tell, but eyeballing it, it seems that the data roughly follows the general shape of a normal distribution based on the curvature of the overlaid tomato-colored line. It’s unclear yet at what point the difference from the normal distribution (especially in this “roughly follows” territory) would make us say that this does not appear to follow a nearly normal distribution.
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") +
geom_qq_line(color = "tomato") +
labs(title = "Q-Q plot for Dairy Queen Calories from Fat")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.
- 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? (Sincesim_normis not a data frame, it can be put directly into thesampleargument and thedataargument can be dropped.)
df_sim_norm <- data.frame(values = sim_norm)
ggplot(df_sim_norm, aes(sample = values)) +
geom_line(stat = "qq") +
geom_qq_line(color = "tomato") +
labs(title = "Q-Q plot for Simulated Sample (Dairy Queen)")Not all the points fall on the line for the simulated sample, just like not all the points fall on the line for the probability plot for the real 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.
qqnormsim(sample = cal_fat, data = dairy_queen)- 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 normal probability plot for the calories from fat at Dairy Queen does look similar to the plots created for the simulated data, however they are not exactly the same. This does have some evidence of “near” normality in the sense that the simulated sample is sort-of similar to the probability plot for the real data, but it’s also evidence against – the plots are not exactly visually the same, despite being somewhat similar they are definitely not a mirror of each other. And, neither closely follows a straight diagonal line – and as we know, any deviations from normality lead to deviations of points from the line. So, this is “pretty close”. I’m just not sure if it’s not close enough to be considered normal.
- Using the same technique, determine whether or not the calories from McDonald’s menu appear to come from a normal distribution.
mcdmean <- mean(mcdonalds$cal_fat)
mcdsd <- sd(mcdonalds$cal_fat)ggplot(mcdonalds, aes(x = cal_fat)) +
geom_histogram(fill = "gold") +
labs(title = "Frequency Histogram - Mcdonalds",
subtitle = "Just like french fries")ggplot(mcdonalds, aes(x = cal_fat)) +
geom_blank() +
geom_histogram(aes(y = ..density..)) +
stat_function(fun = dnorm, args = c(mean = mcdmean, sd = mcdsd), col = "gold") +
labs(title = "Density histogram - Mcdonalds")ggplot(mcdonalds, aes(sample = cal_fat)) +
geom_line(stat = "qq") +
geom_qq_line(color = "gold") +
labs(title = "Q-Q plot for Mcdonalds Calories from Fat")sim_norm_mcd <- rnorm(n = nrow(mcdonalds), mean = mcdmean, sd = mcdsd)df_sim_norm_mcd <- data.frame(values = sim_norm_mcd)
ggplot(df_sim_norm_mcd, aes(sample = values)) +
geom_line(stat = "qq") +
geom_qq_line(color = "gold") +
labs(title = "Q-Q plot for Simulated Sample (Mcdonalds)")qqnormsim(sample = cal_fat, data = mcdonalds)With all these tools and plots, Mcdonalds data looks somewhat close to normal, but Dairy Queen looks slightly closer to normal. Both of them look close to the ‘normal’ line in the Q-Q plot from -1 to 1 standard deviation from the mean.
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().
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.
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.
- 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?
Q1: What is the probability that an item at Mcdonalds will have over 500 calories?
mcdmean_calories <- mean(mcdonalds$calories)
mcdsd_calories <- sd(mcdonalds$calories)
1 - pnorm(q = 500, mean = mcdmean_calories, sd = mcdsd_calories)[1] 0.6337263
mcdonalds |>
filter(calories > 500) |>
summarize(percent = n() / nrow(mcdonalds))# A tibble: 1 × 1
percent
<dbl>
1 0.614
Q2: What is the probability that an item at Taco Bell will have over 500 calories?
tacobell <- fastfood |>
filter(restaurant == "Taco Bell")tbmean_calories <- mean(tacobell$calories)
tbsd_calories <- sd(tacobell$calories)
1 - pnorm(q = 500, mean = tbmean_calories, sd = tbsd_calories)[1] 0.3799298
tacobell |>
filter(calories > 500) |>
summarize(percent = n() / nrow(tacobell))# A tibble: 1 × 1
percent
<dbl>
1 0.374
The second question, relating to the probability of Taco Bell items having calories over 500, was closer in the two methods.
More Practice
- 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?
fastfood |>
group_by(restaurant) |>
summarize(n = n())# A tibble: 8 × 2
restaurant n
<chr> <int>
1 Arbys 55
2 Burger King 70
3 Chick Fil-A 27
4 Dairy Queen 42
5 Mcdonalds 57
6 Sonic 53
7 Subway 96
8 Taco Bell 115
The above provides us a list of all the restaurants in the fastfood dataset and the number of rows associated with them. There’s Arby’s, Burger King, Chick Fil-A, Dairy Queen, Mcdonalds, Sonic, Subway, and Taco Bell. We’ll create tibbles of each of the restaurants that we haven’t created yet (we’ve already filtered to create dataframes for Mcdonalds, Dairy Queen, and Taco Bell).
arbys <- fastfood |> filter(restaurant == "Arbys")
burgerking <- fastfood |> filter(restaurant == "Burger King")
chickfila <- fastfood |> filter(restaurant == "Chick Fil-A")
sonic <- fastfood |> filter(restaurant == "Sonic")
subway <- fastfood |> filter(restaurant == "Subway")ggplot(arbys, aes(sample = sodium)) +
geom_line(stat = "qq") +
geom_qq_line(color = "darkgreen") +
labs(title = "Q-Q plot for Arby's sodium")ggplot(burgerking, aes(sample = sodium)) +
geom_line(stat = "qq") +
geom_qq_line(color = "darkred") +
labs(title = "Q-Q plot for Burger King's sodium")ggplot(chickfila, aes(sample = sodium)) +
geom_line(stat = "qq") +
geom_qq_line(color = "orange") +
labs(title = "Q-Q plot for Chick Fil-A's sodium")ggplot(dairy_queen, aes(sample = sodium)) +
geom_line(stat = "qq") +
geom_qq_line(color = "tomato") +
labs(title = "Q-Q plot for Dairy Queen's sodium")ggplot(mcdonalds, aes(sample = sodium)) +
geom_line(stat = "qq") +
geom_qq_line(color = "gold") +
labs(title = "Q-Q plot for Mcdonald's sodium")ggplot(sonic, aes(sample = sodium)) +
geom_line(stat = "qq") +
geom_qq_line(color = "navy") +
labs(title = "Q-Q plot for Sonic's sodium")ggplot(subway, aes(sample = sodium)) +
geom_line(stat = "qq") +
geom_qq_line(color = "hotpink") +
labs(title = "Q-Q plot fo Subway's sodium")ggplot(tacobell, aes(sample = sodium)) +
geom_line(stat = "qq") +
geom_qq_line(color = "purple") +
labs(title = "Q-Q plot for Taco Bell's sodium")From my current perspective it looks like Chick Fil-A is the closest to normality for Sodium.
- 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?
This is likely the case because sodium (like many other variables in the fastfood dataset) are reported as whole numbers (integers) rather than as the continuous normal distribution would (numbers with decimals),
- 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.
It appears that for Chick Fil-A, the distribution for the total carbohydrates variable (total_carb) is right skewed.
ggplot(chickfila, aes(sample = total_carb)) +
geom_line(stat = "qq") +
geom_qq_line(color = "orange") +
labs(title = "Q-Q plot for Chick Fil-A's Total Carbohydrates")chickcarbmean <- mean(chickfila$total_carb)
chickcarbsd <- sd(chickfila$total_carb)ggplot(chickfila, aes(x = total_carb)) +
geom_histogram(fill = "orange") +
labs(title = "Frequency Histogram - Carbs at Chick Fil-A")ggplot(chickfila, aes(x = total_carb)) +
geom_blank() +
geom_histogram(aes(y = ..density..)) +
stat_function(
fun = dnorm, args = c(
mean = chickcarbmean, sd = chickcarbsd), col = "orange") +
labs(title = "Density histogram - Carbs at Chick Fil-A")sim_norm_chick <- rnorm(n = nrow(chickfila),
mean = chickcarbmean, sd = chickcarbsd)sim_norm_chick <- data.frame(values = sim_norm_chick)
ggplot(sim_norm_chick, aes(sample = values)) +
geom_line(stat = "qq") +
geom_qq_line(color = "orange") +
labs(title = "Q-Q plot for Simulated Sample (Chick Fil-A Carbs)")qqnormsim(sample = total_carb, data = chickfila)