1.17 Visualizing Data Distributions

With the Cappuccino Index

Introduction

The Cappuccino Index

James Hoffmann is a YouTuber who explores coffee from many different angles. In a recent video he explored how long a barista would need to work to pay for a small cappuccino.

Coffee, as a part of our economy, as an industry, is full of these awkward questions that I do think are worth asking.

In the video, James presents the cappuccino index, which answers this at a country level.

There are some important caveats, such as tips being excluded.

Data Source & Description

Data Dictionary - cafe

variable class description
country character The country of the cafe.
city character The city of the cafe.
urban logical Whether the cafe is in an urban area.
suburban logical Whether the cafe is in a suburban area.
rural logical Whether the cafe is in a rural area.
hourly_wage_gbp double The hourly wage of a barista working in the cafe, converted to British pounds.
price_gbp double The price of a small cappuccino from the cafe, converted to British pounds.
original_currency character The original currency used by the cafe.
price double The price of a small cappuccino from the cafe, in the original currency.
hourly_wage double The hourly wage of a barista working in the cafe, in the original currency.

Data Dictionary - cappuccino_index

variable class description
country character Name of country for which cappuccino index was calculated.
index double The cappuccino index: the time in minutes a barista needs to work to afford a small cappuccino in their country.
n integer Number of cafes that were included in the calculation of the index.
minutes double The number of whole minutes in index.
seconds double The remaining number of seconds in index.
index_as_time character Index formatted as minutes and seconds, i.e., MM:SS.

Read in the Data

cafe <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/main/data/2026/2026-09-08/cafe.csv')
cappuccino_index <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/main/data/2026/2026-09-08/cappuccino_index.csv')


cafe$country <- gsub("\u00a0", " ", cafe$country)
cappuccino_index$country <- gsub("\u00a0", " ", cappuccino_index$country)
1
Replace non-breaking spaces with regular spaces

Categorical Distributions

Participating Countries

cafe_plot <- cafe |>
  count(country) |>
  mutate(prop = n/sum(n)) |>
  arrange(desc(prop)) |>
  head(10)
cafe_plot <- bind_rows(
  tibble(country = "Other",
         n = 2594 - sum(cafe_plot$n),
         prop = 1-sum(cafe_plot$prop)),
  cafe_plot) |>
  mutate(country = factor(country, levels = country, ordered = T))
  
head(cafe_plot)
1
count(var) is a shortcut for group_by(var) |> summarize(n = n()) |> ungroup() - it counts up the number of rows with each value of var.
2
Calculate the proportion from the number of observations with a specific value and total number of observations
3
Sort the dataset by desc(prop)
4
Take the top 10 rows – there are too many countries to show
5
Create an “Other” row that includes everything else
6
Reorder the levels of country based on decreasing proportion
# A tibble: 6 × 3
  country       n   prop
  <ord>     <dbl>  <dbl>
1 Other       610 0.235 
2 USA         600 0.231 
3 UK          595 0.229 
4 Australia   171 0.0659
5 Germany     167 0.0644
6 Canada      130 0.0501

Participating Countries

ggplot(cafe_plot,
       aes(x = country,
           fill = country,
           y = prop)) +
  geom_col() +
  coord_flip() +
  guides(fill = 'none') +
  ylab("Proportion of Observations") +
  xlab("") +
  ggtitle("Cappuccino Index Data by Country")
1
Show country on the x-axis, fill by country as well, then show prop on the y-axis.
2
Create columns (rectangles)
3
Flip x and y so that labels are horizontal and more easily read
4
Remove the fill legend because it’s equivalent to the x (now y) axis.
5
Set axis labels
6
Set plot title.

A bar chart showing number of cappuccino observations taken by country.

Rural vs. Urban

Are the categories mutually exclusive?

cafe |>
filter(
  urban + rural + suburban > 1
) |>
  select(1:5)
# A tibble: 63 × 5
   country     city       urban suburban rural
   <chr>       <chr>      <lgl> <lgl>    <lgl>
 1 Switzerland Aarau      TRUE  TRUE     FALSE
 2 Norway      Bergen     TRUE  TRUE     FALSE
 3 Netherlands Rotterdam  TRUE  TRUE     FALSE
 4 USA         Branson    TRUE  TRUE     FALSE
 5 UK          Falmouth   FALSE TRUE     TRUE 
 6 USA         Merced, CA TRUE  FALSE    TRUE 
 7 USA         Boston     TRUE  TRUE     FALSE
 8 UK          Leeds      TRUE  TRUE     FALSE
 9 UK          Cardiff    TRUE  TRUE     FALSE
10 USA         Normal, IL TRUE  TRUE     FALSE
# ℹ 53 more rows

Ok, well that’s odd, but let’s just work around it for now

Rural vs. Urban

First, we have to rearrange the data so that density is a single variable.

cafe_density <- cafe |>
  pivot_longer(c(3:5), 
               names_to = "density") |>
  filter(value) |>
  select(country, density, ends_with("gbp"))
cafe_density
# A tibble: 2,659 × 4
   country      density  hourly_wage_gbp price_gbp
   <chr>        <chr>              <dbl>     <dbl>
 1 Denmark      urban              16.0      10.3 
 2 China        urban               3.29      9.44
 3 USA          suburban           13.2       8.89
 4 Switzerland  rural              24.5       8.26
 5 Denmark      urban              16.0       7.45
 6 Singapore    urban              11.2       6.89
 7 France       urban              12.8       6.85
 8 Switzerland  suburban           21.1       6.24
 9 Saudi Arabia urban               4.16      6.33
10 Denmark      urban              21.7       6.3 
# ℹ 2,649 more rows

Stacked Bar Chart: Rural vs. Urban

ggplot(cafe_density,
       aes(x = 1,
           fill = density)) +
  geom_bar(position = "fill") +
  xlab("") + ylab("Proportion") +
  coord_flip() +
  theme(axis.text.y = element_blank(),
        axis.ticks.y = element_blank())
1
put all columns in the same location
2
color by density – urban, suburban, rural
3
plot the bars on top of each other, then scale to 1 so that each bar is sized by the proportion of the data in that bar
4
Set axis labels (or lack thereof for x)
5
Flip the axes (so that the plot fits on the slide – not actually necessary)
6
Remove x axis text and ticks because there is nothing on the x-axis.

A stacked bar chart showing three categories: urban, suburban, and rural. Urban makes up nearly 70% of the observations, suburban makes up another 24% of the observations, and rural accounts for the remaining 6% of the observations. Some locations fall into two categories.

Pie Chart: Rural vs. Urban

ggplot(cafe_density,
       aes(x = 1, 
           fill = density)) + 
  geom_bar(position = "fill") + 
  coord_polar(theta = "y") +
  theme_void()
1
Set coordinates to polar and specify which variable is theta (angle). This transforms a stacked bar chart into a pie chart.
2
Remove grid, axis text, etc.

A stacked bar chart showing three categories: urban, suburban, and rural. Urban makes up nearly 70% of the observations, suburban makes up another 24% of the observations, and rural accounts for the remaining 6% of the observations. Some locations fall into two categories.

Numeric Distributions

Data Wrangling

cafe_english <- cafe |>
  filter(country %in% c("Australia", "USA", "UK"))

cafe_summary <- cafe_english |>
  group_by(country) |>
  summarize(mean = mean(price_gbp), median = median(price_gbp)) |>
  pivot_longer(-country, names_to="summary") |>
  mutate(summary = factor(summary))
1
Get only the UK, US, and Australia
2
Summarize price_gbp, getting the median and mean
3
Pivot longer, so that we have long-form data with the summary name as the column name. This makes plotting easier.

ECDFs

An empirical CDF of the cost of a cappuccino in Australia, the USA, and the UK, with all costs represented in british pounds. Australia has much cheaper coffee than the USA and the UK, though the US has more variability than the UK in price at the lower end of the distribution; after the median, however, the US and the UK have similarly priced coffee.

  • Shows all of the data in the distribution
  • Continuous variables will look relatively smooth for large enough \(n\)
  • Discrete variables will have “steps”
  • Hard to see the mean, variability, range

Histograms - Cost of Cappuccino

cafe |>
  filter(country %in% c("USA", "UK", "Australia")) |>
  ggplot(aes(x = price_gbp, fill = country)) + 
  geom_histogram(binwidth = .2) + 
  guides(fill = "none") + 
  facet_grid(country~., scales = "free_y")
1
Setting scales = "free_y" allows the y-axis scale to vary between the different countries, de-emphasizing the lower amount of data in Australia relative to the other two countries.

Three histograms showing the cost of a small cappuccino in Australia, the UK, and the USA. It is clear that coffee is cheaper in Australia relative to the other two countries.

Histograms

ggplot(cafe_english, 
       aes(x = price_gbp, 
           fill = country)) + 
  geom_histogram(boundary = 0, closed="left") +
  geom_segment(
    data = cafe_summary,
    aes(x = value, xend = value,
        y = 0, yend = Inf,
        linetype = summary), 
    color = "black") +
  facet_grid(country~., scales = "free_y") +
  guides(fill = 'none')

Histograms of the cost of a cappuccino in Australia, the USA, and the UK, with all costs represented in british pounds. Australia has much cheaper coffee than the USA and the UK, though the US has more variability than the UK in price at the lower end of the distribution; after the median, however, the US and the UK have similarly priced coffee.

  • Easy to see distribution center and spread
  • Sensitive to bin width/number of bins

Histograms

ggplot(cafe_english, 
       aes(x = price_gbp, 
           fill = country)) + 
  geom_histogram(boundary = 0, closed="left", binwidth = 0.05) + 
  geom_segment(
    data = cafe_summary,
    aes(x = value, xend = value,
        y = 0, yend = Inf,
        linetype = summary), color = "black") +
  facet_grid(country~., scales = "free_y") +
  guides(fill = 'none')

A histogram of coffee prices in the UK only, using a binwidth of 0.05 pounds. This binwidth shows that it is uncommon to have prices which are not multiples of 0.10.

  • Easy to see distribution center and spread
  • Sensitive to bin width/number of bins
    • Extra-sensitive if data are discrete or rounded

Density Plots

ggplot(cafe_english, 
       aes(x = price_gbp, 
           color = country)) + 
  geom_density(adjust = 2) 

A density plot of coffee prices in the US, UK, and Australia.

  • Smoothed out version of a histogram
  • Masks rounded/discrete variables

Density Plots

ggplot(cafe_english, 
       aes(x = price_gbp, 
           color = country)) + 
  geom_density(adjust = .5) 

A density plot of coffee prices in the US, UK, and Australia.

  • Smoothed out version of a histogram
  • Masks rounded/discrete variables
  • With smaller bandwidth/adjustment, discrete variables look like zigzags.
  • Adjust bandwidth using geom_density(adjust=XXX)
    • Try values of XXX of 0.5, 1.5 to start

Box Plots

ggplot(cafe_english, 
       aes(x = country, 
           y = price_gbp)) + 
  geom_boxplot()

  • Box:
    • lower: 25th percentile
    • upper: 75th percentile
    • middle: median, 50th percentile
  • Whiskers:
    • smallest observation that is greater than or equal to (lower hinge - 1.5 * (upper - lower))
    • largest observation that is less than or equal to (upper hinge + 1.5 * (upper - lower))
  • Outliers: anything not covered by the whiskers are shown as individual points

Violin Plots

ggplot(
  cafe_english, 
  aes(x = country, 
      y = price_gbp, 
      fill = country)) + 
  geom_violin(adjust = 0.75) + 
  geom_boxplot(
    width=.1, 
    fill = "white",
    outliers = FALSE) + 
  guides(fill = "none")

  • Density curve plotted vertically, then mirrored
  • Often shown with a boxplot (or quantile lines) overlaid on top