2  Histograms

Graphs in this chapter use ggrewindr::theme_oksoda(), built from OK Soda cans (1993 to 1995): a brushed silver background, a black frame, a gray comic panel, OK red marks and title, slate and brick accents, and a Cousine title.

Requirements:

✅ a numeric (continuous) variable


2.1 Description

A histogram is a graph that displays numerical data spread over a continuous interval. Each bar shows the frequency of data points within a specific range. Unlike bar graphs, histograms do not have gaps between the bars, indicating that data covers a continuous interval. The x-axis displays the variable range, while the y-axis represents observation frequency.

Unlike a typical bar graph, a histogram shows the shape of a variable’s distribution. We can check its ‘normality’ (i.e. are the bars symmetrical, with a single peak in the middle of the x axis? Or do the bars form multiple peaks?). We can also check its ‘skewness’ (i.e., is there a long ‘tail’ of bars with decreasing length on either end of the x axis?).

In ggplot2, histograms can be built using geom_histogram().

2.2 Set up

PACKAGES

Install packages.

show/hide
library(ggplot2)
library(dplyr) # for tibble() and data manipulation

DATA

OK Soda was Coca-Cola’s 1993 soda for Gen X, sold in gray comic book cans with slogans like “Things are going to be OK.” If you don’t remember this, it’s worth reading this article in Mental Floss or watching these hilarious commercials on YouTube.

We’ll simulate one day of sales at 300 test market stores with rnorm(), rounding each store’s sales to a whole number of cans. Setting the seed with set.seed() means you’ll get the same 300 values every time you run the code below.

show/hide
set.seed(1014) # same 300 stores every time the code runs
ok_soda_sales <- tibble(
  store_id = 1:300, # 300 different stores, one row each
  cans = round(
    rnorm(n = 300, mean = 45, sd = 12) # cans sold in one day (centered on 45)
    )
)
glimpse(ok_soda_sales)
#> Rows: 300
#> Columns: 2
#> $ store_id <int> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, …
#> $ cans     <dbl> 28, 48, 16, 45, 52, 59, 23, 42,…

2.3 Distribution

You don’t have to be a math whiz or statistician to read a histogram, but it helps to know what shape to expect. Because we generated cans ourselves, we already know the answer. Every value came from a normal distribution with a mean of 45 cans and a standard deviation of 12 cans. Below we’ll move from the numbers, to a picture, to the formula. Once we know what the expected shape looks like, we’ll change the data and see what the unexpected does to it.

COUNT IT

Start with the first ten stores.

show/hide
head(ok_soda_sales$cans, 10)
#>  [1] 28 48 16 45 52 59 23 42 42 42

Most of these values land within 12 cans of 45, and a few (like 16 and 23) sit further out. Let’s sort all 300 stores into three ranges: below, within, and above one standard deviation of the mean. The middle range holds most of the stores.

To find the edges of these ranges, we subtract and add one standard deviation to the mean:

  • Lower edge: \(45 - 12 = 33\) cans

  • Upper edge: \(45 + 12 = 57\) cans

A store with fewer than 33 cans is below one standard deviation. A store with 33 to 57 cans is within it, and a store with 58 or more cans is above it. In the code below, cut() places the breaks half a can past each edge (32.5 and 57.5), so a store with exactly 33 or 57 cans lands in the middle range.

show/hide
ok_soda_ranges <- ok_soda_sales |>
  mutate(range = cut(cans,
    breaks = c(-Inf, 32.5, 57.5, Inf),
    labels = c("under 33", "33 to 57", "58 and over"))) |>
  count(range)
ok_soda_ranges

DRAW IT

A bar model shows these counts as parts of one whole. The full bar is all 300 stores, and the middle part takes up roughly two thirds of it.

show/hide
ggplot(data = ok_soda_ranges,
    aes(x = n, y = "300 stores", fill = range)) +
  geom_col(position = position_stack(reverse = TRUE),
    color = "white") +
  geom_text(aes(label = n), color = "white",
    position = position_stack(vjust = 0.5, reverse = TRUE)) +
  labs(x = "Number of stores", y = NULL,
    fill = "Cans sold")

A histogram is the same idea, cut into 30 thinner pieces and stood upright. The dashed lines below mark 33 and 57 cans, the edges of the middle part of the bar model.

show/hide
ggplot(data = ok_soda_sales,
    aes(x = cans)) +
  geom_histogram() +
  geom_vline(xintercept = c(33, 57), linetype = "dashed") +
  labs(x = "Cans sold", y = "Number of stores")

NAME IT

The rnorm() call that created the data is a single statement:

\[ X \sim \text{Normal}(\mu = 45, \sigma = 12) \]

The mean (\(\mu\)) sets where the tallest bars sit on the x axis. The standard deviation (\(\sigma\)) sets how far the bars spread out from it. For a normal distribution, roughly 68% of values fall within one \(\sigma\) of \(\mu\) and 95% fall within two. Our simulated stores come close: 66% are within one \(\sigma\) and 95% are within two.

The small gap between the rule and our sample is just sampling variation. Change the number in set.seed() and the bars shift, but the bell shape stays centered near 45 cans.

CHANGE IT

So far the histogram shows exactly what we expect: one bell centered on 45 cans. Now we’ll change the data. Suppose the last 60 stores sit near college campuses, where OK Soda sold far better (about 85 cans a day). We expect a second hump of bars on the right side of the graph.

show/hide
set.seed(1014)
ok_soda_campus <- ok_soda_sales
ok_soda_campus$cans[241:300] <- round(
  rnorm(n = 60, mean = 85, sd = 8) # 60 campus stores
  )
summarise(ok_soda_campus,
  mean = mean(cans), sd = sd(cans), median = median(cans))

The dashed line below marks the new mean.

show/hide
ggplot(data = ok_soda_campus,
    aes(x = cans)) +
  geom_histogram(binwidth = 3, center = 45) +
  geom_vline(xintercept = mean(ok_soda_campus$cans), linetype = "dashed") +
  labs(x = "Cans sold", y = "Number of stores")

The campus stores pull the mean up to about 53 cans and stretch the standard deviation to almost 20. The numbers alone still look ordinary: 67% of stores fall within one standard deviation of the mean, right where the 68% rule says they should. The histogram tells a different story. It has two peaks, and the mean sits between them, describing neither the typical store nor the typical campus store. I’ve found this is the main reason to graph a distribution before summarizing it. A mean and standard deviation can’t show a second group, but the bars can.

2.4 Grammar

CODE

  1. Create labels with labs()

  2. Initialize the graph with ggplot() and provide data

  3. Assign cans to the x

  4. Add the geom_histogram()

  5. Set the width of each bin (binwidth = 3) and center one bin on 45 cans (center = 45)

show/hide
labs_histogram <- labs(
  title = "OK Soda",
  caption = "Simulated data",
  subtitle = "Cans sold per store in one day",
  x = "Cans sold",
  y = "Number of stores")

ggp2_hist <- ggplot(data = ok_soda_sales,
      aes(x = cans)) + 
      geom_histogram(binwidth = 3, center = 45) 

ggp2_hist + 
  labs_histogram

GRAPH

The standard number of bins is 30, but ‘you should always override this value, exploring multiple widths to find the best to illustrate the stories in your data.’

show/hide
ggp2_hist_bins45 <- ggplot(data = ok_soda_sales,
     aes(x = cans)) + 
     geom_histogram(bins = 45) 

ggp2_hist_bins45 + 
  labs_histogram + 
  labs(subtitle = "45 bins")

ggp2_hist_bins15 <- ggplot(data = ok_soda_sales,
     aes(x = cans)) + 
     geom_histogram(bins = 15) 

ggp2_hist_bins15 + 
  labs_histogram + 
  labs(subtitle = "15 bins")