Homework 4

Relationships, Log Transformations, Time Trends, and Career Preparation

Homework 4 based on Lectures 8 and 9, with R coding using Gapminder data read from a CSV file.
Author

Byeong-Hak Choe

Published

November 11, 2026

Homework 4 Question Scores

The table shows the fraction of available points earned on each question, on a 0–1 scale. It combines both sections, using each student’s highest-scoring attempt and recording zero credit for non-submissions. Late-submission adjustments affect the recorded total score, not these question-level fractions.

Instructions

This homework focuses on Lecture 8 and includes two Lecture 9 career questions. Answer all 32 questions, worth 100 points.

  • Concepts: 50 points. Questions 1–13 are multiple-choice questions; Questions 14–16 are conceptual fill-in-the-blank questions.
  • R programming: 50 points. Questions 17–32 each contain one R-code blank and use the gapminder data frame read from the CSV file below, or a setup subset derived from it.
  • Questions 12 and 13 connect the Andy and Oliver and Marcie career sessions, respectively, with Prof. Choe’s thoughts in Lecture 9.

For each multiple-choice question, select the one best answer. For a conceptual blank, enter only the requested term or number. For a coding question, enter only the R code that replaces [?], not the entire code block. Include quotation marks when the missing code is a character string.

A coding blank may require a complete condition, aesthetic mapping, or plot layer. Read the requested result carefully and compare your completed code with the target visualization. The completed code used to generate each target is hidden.

Run the setup below once, then write and test your answers in an R script. Each coding question starts from the original setup objects and can be completed independently. Plot labels, axis formatting, legend settings, and palette choices already supplied in a code block are part of the template; keep them as provided. They are not additional blanks.

Use the course materials and R methods covered through Lecture 8, together with the specified Lecture 9 career material. Colored group comparisons use a ggthemes colorblind-friendly palette. Labels, shapes, line types, and panels provide additional group cues where appropriate.

Due: Tuesday, November 24, 2026, at 11:59 PM Eastern Time.

Attempts: Two attempts are allowed. Your highest attempt score will be recorded.

Submission: Submit your answers through the Brightspace quiz.

ImportantGenerative AI is not permitted

Complete this homework independently. Do not use generative AI tools to generate, revise, explain, debug, or check your answers or R code. Use the lectures, classwork, and your own course notes. Please ask Prof. Choe if you need help.

Setup and Data

All coding questions use the gapminder data frame. Read the CSV file directly from the web and create the subsets below.

library(tidyverse)
library(ggthemes)

gapminder <- read_csv(
  "https://bcdanl.github.io/data/gapminder.csv"
)

countries_2007 <- gapminder |>
  filter(year == 2007)

three_continents <- countries_2007 |>
  filter(continent == "Americas" |
         continent == "Asia" |
         continent == "Europe")

If ggthemes is missing, run install.packages("ggthemes") once before loading it.

The gapminder Data Frame

gapminder has 1,704 country-year records for 142 countries, with observations every five years from 1952 through 2007 (12 recorded years per country). Each row represents one country in one recorded year, not one person. Countries receive equal weight in the plots; population is not used as a plot weight.

Variable descriptions

Variable Description
country Country name.
continent Continent category in the dataset.
year Year of the country record, recorded every five years: 1952, 1957, and so on through 2007.
lifeExp Life expectancy at birth, in years. This is a country-level measure, not an individual person’s age.
pop Country population, in people.
gdpPercap GDP per person, in the dataset’s dollar units.

Setup subsets

  • countries_2007: the 142 country records for 2007.
  • three_continents: the 88 records for the Americas, Asia, and Europe in 2007, including the United States. These groups are used for grouped fitted curves; Oceania has only two records in the 2007 subset.

All GDP and population values used in the logarithmic plots are positive. Connecting two recorded years with a line does not add observations for the intervening years.

Part I: Multiple Choice — Concepts

Question 1

3 points · Lecture 8

This scatterplot uses GDP per person on the horizontal axis and life expectancy on the vertical axis. What does one point represent?

Each point places one country’s 2007 GDP per person and life expectancy. Color and shape identify continent.

  1. One country’s GDP-per-person and life-expectancy values in 2007.
  2. One person’s income and eventual age at death.
  3. The total population of one continent across all years.
  4. The change in a country’s GDP between two years.

a. One country’s GDP-per-person and life-expectancy values in 2007.

Each row of countries_2007 is one country in 2007. The two coordinates come from that row’s national measures. The graph does not contain a separate observation for every person or show each country’s change over time.

Question 2

3 points · Lecture 8

The curve summarizes the relationship between GDP per person and life expectancy in 2007. Which description best matches its direction and shape?

Country life expectancy in 2007 plotted against GDP per person on an ordinary dollar axis. A black smooth curve rises quickly at lower GDP values and becomes flatter at higher GDP values, with points scattered around it.

  1. Life expectancy generally decreases as GDP per person increases, and the decrease becomes faster at higher GDP values.
  2. There is no overall direction because the curve becomes flatter at higher GDP values.
  3. Life expectancy generally increases as GDP per person increases, but the upward curve becomes flatter at higher GDP values.
  4. Life expectancy first decreases and then increases as GDP per person increases.

c. Life expectancy generally increases as GDP per person increases, but the upward curve becomes flatter at higher GDP values.

The curve rises overall, indicating a positive association. It rises more quickly at lower GDP-per-person values and then flattens. A flatter portion still has a direction; it does not mean that the entire plot lacks an association. This country comparison does not establish that changing GDP alone causes the pattern.

Question 3

4 points · Lecture 8

The straight fitted line summarizes life expectancy against base-10 log GDP per person. Choose a GDP-per-person value on the horizontal axis. What does the fitted line tell us about life expectancy at that value?

Country-level scatterplot of life expectancy against log10 GDP per person, with one upward fitted straight line.

  1. The life expectancy that every country at that GDP value must have.
  2. The median GDP per person of the countries above the line.
  3. A guaranteed life expectancy after a country adopts a particular policy.
  4. An estimated average life expectancy at that GDP-per-person value, based on the plotted data and fitted model.

d. An estimated average life expectancy at that GDP-per-person value, based on the plotted data and fitted model.

The fitted line estimates an average outcome at a given input. Individual country observations may lie above or below it. The line is not an individual guarantee, an exact median, or evidence of a policy’s causal effect.

Question 4

4 points · Lecture 8

The grey ribbon around the fitted line is the default 95% confidence ribbon. Some country points fall outside it. Which interpretation is appropriate?

A fitted straight line and grey confidence ribbon summarize the average relationship. Country observations are scattered on both sides, including outside the ribbon.

  1. The ribbon shows uncertainty around the estimated average relationship; it is not a band required to contain 95% of individual country observations.
  2. The graph is incorrect unless exactly 95% of all country points lie inside the ribbon.
  3. A point outside the ribbon must be a data-entry error.
  4. The ribbon gives the full minimum-to-maximum range of country life expectancy at every GDP value.

a. The ribbon shows uncertainty around the estimated average relationship; it is not a band required to contain 95% of individual country observations.

The ribbon concerns uncertainty in the estimated average outcome at a given input, under the fitting method’s assumptions. Variation among individual countries is a different issue. Points outside the ribbon are not automatically mistakes.

Question 5

3 points · Lecture 8

This plot includes the 2007 countries with GDP per person between $2,000 and $6,000. What does the vertical spread of the points around the fitted line show?

Thirty countries with GDP per person between 2,000 and 6,000 dollars have life expectancies ranging from about 40 to 76 years. A straight fitted line summarizes the pattern, with substantial vertical spread among the points.

  1. Countries at similar GDP-per-person values have similar life expectancies, so the line captures almost all country differences.
  2. The spread measures how much each country’s GDP per person changed between 1952 and 2007.
  3. Countries with similar GDP per person can have quite different life expectancies, even though the line summarizes an overall pattern.
  4. The distance from a point to the line measures the uncertainty in that country’s recorded GDP per person.

c. Countries with similar GDP per person can have quite different life expectancies, even though the line summarizes an overall pattern.

Different vertical positions at similar horizontal positions show variation in life expectancy among countries with similar GDP per person. The fitted line summarizes the relationship but does not capture every country difference. These are different countries in one year, rather than one country over time.

Question 6

4 points · Lecture 8

The United States and South Africa are labeled in this 2007 country comparison. Which statement best compares their life expectancies with the fitted pattern?

Life expectancy against log10 GDP per person for countries in 2007, with a fitted straight line. The United States and South Africa are labeled and marked with blue triangles. Both are below the fitted line; South Africa is much farther below it.

  1. Both countries lie above the fitted line, with South Africa farther from the fitted pattern at its GDP-per-person value.
  2. Both countries lie below the fitted line, with South Africa farther from the fitted pattern at its GDP-per-person value.
  3. Both countries lie below the fitted line, with the United States farther from the fitted pattern at its GDP-per-person value.
  4. South Africa lies above the fitted line, while the United States lies below the fitted pattern at its GDP-per-person value.

b. Both countries lie below the fitted line, with South Africa farther from the fitted pattern at its GDP-per-person value.

Both points are below the fitted line, but South Africa is much farther below it. South Africa’s life expectancy is therefore more unusual relative to the fitted pattern at its GDP-per-person value. The United States provides a familiar comparison with a much smaller deviation from the fitted pattern. An unusual point calls for examining the record and context, rather than assuming an error or deleting it. This single-year comparison does not identify the cause of either country’s position.

Question 7

3 points · Lecture 8

This chart includes the United States and other countries. Each continent is identified by both a point’s color and shape. How do the point shapes help when the chart is printed in black and white?

The Americas, Asia, and Europe are identified by distinct point shapes as well as color, with a labeled legend. The Americas include the United States.

  1. Changing the symbols changes the numerical values of life expectancy.
  2. Every symbol becomes a separate country-year dataset.
  3. The shapes remove the need to name the groups in the legend.
  4. The point symbols provide another way to distinguish the continent groups when colors are difficult to distinguish.

d. The point symbols provide another way to distinguish the continent groups when colors are difficult to distinguish.

Shape is an additional visual cue. It helps identify groups when color alone is insufficient, while the legend explains what each symbol means. The data values do not change.

Question 8

4 points · Lecture 8

The three panels use the same horizontal and vertical scales. Which comparison of their fitted straight lines is correct?

The Americas, Asia, and Europe appear in separate panels with identical GDP-per-person and life-expectancy scales. GDP per person is measured in ten-thousand-dollar units. Each has an upward fitted straight line. Asia’s line rises more steeply than the Americas and Europe lines.

  1. The Americas’ fitted line has the steepest upward slope.
  2. Asia’s fitted line has the steepest upward slope.
  3. Europe’s fitted line has the steepest upward slope.
  4. The fitted lines have the same slope because they all rise.

b. Asia’s fitted line has the steepest upward slope.

With identical axis scales, the Asia panel’s line rises most sharply as GDP per person increases. The Americas panel includes the United States, together with other countries in the region. Steepness describes change along the displayed axes; it does not identify which group’s points cluster most tightly around its line. A steeper slope alone does not establish a stronger association or a causal effect.

Question 9

3 points · Lecture 8

On an ordinary dollar axis, the increase from $4,000 to $8,000 is smaller than the increase from $12,000 to $24,000. How do these two changes compare on a logarithmic axis?

  1. The second must remain three times as wide because it adds three times as many dollars.
  2. The first becomes wider because it begins at a smaller amount.
  3. They have equal horizontal distances because both multiply the starting value by two.
  4. They collapse to zero distance because logarithms remove all differences.

c. They have equal horizontal distances because both multiply the starting value by two.

Both changes double the starting value: 8,000/4,000 = 2 and 24,000/12,000 = 2. Equal multiplicative or percentage changes have equal spacing on a log axis, even when their absolute dollar increases differ.

Question 10

3 points · Lecture 8

A scatterplot’s horizontal axis is labeled log10 GDP per person. The axis position 3 corresponds to $1,000, and position 4 corresponds to $10,000. What does moving from horizontal position 3 to position 4 mean?

  1. GDP per person increases by exactly one dollar.
  2. GDP per person becomes ten times as large; the vertical life-expectancy axis is still measured in years.
  3. Life expectancy must become ten times as large.
  4. Both axes have necessarily been transformed into logarithms.

b. GDP per person becomes ten times as large; the vertical life-expectancy axis is still measured in years.

The supplied values give a ratio of 10,000/1,000 = 10. A transformation of the horizontal variable does not automatically transform the vertical variable.

Question 11

3 points · Lecture 8

The gapminder data frame records each country at five-year intervals. A line connects a country’s life-expectancy point for 1952 to its point for 1957. What can a reader conclude about 1953–1956 from that connecting segment alone?

Canada and the United States each have life-expectancy records every five years from 1952 to 2007. Separate lines connect each country’s recorded points; colors, point shapes, and line types distinguish the countries.

  1. The data frame contains an annual life-expectancy record at every point on the segment.
  2. Life expectancy must have stayed exactly equal to the 1952 value until 1957.
  3. The line forecasts life expectancy for years after 2007.
  4. The segment connects the recorded endpoints; it does not supply recorded annual values for 1953–1956.

d. The segment connects the recorded endpoints; it does not supply recorded annual values for 1953–1956.

A line joins records in year order. It does not create records for years between the five-year observations or establish a forecast beyond the recorded period. The intermediate points on the drawn segment are not additional rows in gapminder.

Question 12

2 points · Lecture 9

Andy and Oliver, together with Prof. Choe’s thoughts: Leah has finished a course project and wants to apply for internships this month. She has little interview experience. Which plan best follows the career preparation advice in Lecture 9?

  1. Practice explaining her project decisions, seek Career Center feedback, and apply to suitable openings while reaching out to campus contacts.
  2. Build a second project using an employer’s tools, then begin applications and interview preparation once the new project is complete.
  3. Concentrate on sending applications with a shared résumé, and prepare project explanations after employers invite her to interview.
  4. Seek alumni referrals for a small set of roles, and use feedback from her first interviews to decide what preparation to do.

a. Practice explaining her project decisions, seek Career Center feedback, and apply to suitable openings while reaching out to campus contacts.

Andy’s example shows the value of a meaningful project a student can explain in depth. Oliver emphasized applications and deliberate interview practice, and Prof. Choe recommends combining campus outreach with preparation. Leah can use her completed project now while practicing and applying. The other plans include useful activities, but each postpones some of that preparation or makes it depend on a later event.

Course source: Lecture 9: Projects and first internships and Finding opportunities.

Question 13

3 points · Lecture 9

Marcie, together with Prof. Choe’s thoughts: Mateo has taken an introductory data course and is interested in product marketing and customer education. Which next learning goal best reflects the value of data skills in those roles, as discussed in Lecture 9?

  1. Learn a company’s reporting software so he can reproduce its existing dashboards and prepare reports in the formats its teams use.
  2. Use data to answer a customer question, check the evidence, and explain the findings and their limits to a nontechnical audience.
  3. Develop presentation and marketing skills first, then return to data analysis when the requirements of a particular position become clearer.
  4. Build a portfolio of advanced statistical models to demonstrate technical depth and distinguish his quantitative skills from those of other marketing applicants.

b. Use data to answer a customer question, check the evidence, and explain the findings and their limits to a nontechnical audience.

Marcie continued using data as her work moved into product marketing and customer education. Prof. Choe connects that experience to transferable quantitative reasoning, communication, and business judgment. Answer b combines these skills in a relevant customer problem. Software familiarity, presentations, and statistical depth can also be useful, but none of the other goals connects data reasoning with the audience’s question as directly.

Course source: Lecture 9: Daily work and workplace fit and Data foundations across careers.

Part II: Fill in the Blank — Concepts

Question 14

2 points · Lecture 8

In a relationship plot, the variable whose values we want to understand or predict is called the [?] variable. In the country example, life expectancy plays this role. Enter the term used in Lecture 8.

outcome

Life expectancy is the outcome, plotted on the y-axis in this example. The explanatory input is GDP per person. “Response” or “dependent” variable is equivalent terminology, but the lecture uses “outcome.”

Question 15

3 points · Lecture 8

A logarithmic axis gives the same horizontal distance to the change from $2,000 to $6,000 as to the change from $6,000 to $18,000. Each change multiplies the starting value by [?]. Enter one number.

3

6,000/2,000 = 3 and 18,000/6,000 = 3. Equal ratios have equal spacing on a log axis. The absolute increases, $4,000 and $12,000, are different.

Question 16

3 points · Lecture 8

An illustrative country’s GDP per person rises from $8,000 to $10,000. The percentage increase is [?]%. Enter only the number, without a percent sign.

25

(10,000 - 8,000)/8,000 × 100 = 25%. The absolute increase is $2,000, while the relative increase is 25%. These illustrative values distinguish dollar changes from the percentage changes emphasized by log spacing.

Part III: Fill in the Blank — R Programming

Question 17

3 points · Lecture 8

Reproduce the 2007 comparison for countries in the Americas, including the United States.

americas_2007 <- gapminder |>
  filter(year == 2007,
         continent == "Americas")

ggplot(data = americas_2007,
       mapping = [?]) +
  geom_point(color = "steelblue",
             alpha = 0.65,
             size = 2) +
  labs(x = "GDP per person (US$)",
       y = "Life expectancy (years)")

Target visualization:

GDP per person and life expectancy for 25 countries in the Americas in 2007, including the United States, shown as blue points on ordinary numeric axes.

aes(x = gdpPercap,
    y = lifeExp)

The horizontal positions use gdpPercap and the vertical positions use lifeExp. The supplied filter selects 25 country records from the Americas in 2007, including the United States, so each point is one country in that year. Neither axis is transformed in this plot.

Question 18

2 points · Lecture 8

Reproduce this country-year scatterplot with points at 70% opacity.

ggplot(data = gapminder,
       mapping = aes(x = log10(gdpPercap),
                     y = lifeExp,
                     color = continent,
                     shape = continent)) +
  geom_point([?],
             size = 1.1) +
  scale_color_colorblind() +
  labs(x = "log10(GDP per person)",
       y = "Life expectancy (years)",
       color = "Continent",
       shape = "Continent")

Target visualization:

All 1,704 country-year observations form a dense scatterplot of life expectancy against log10 GDP per person. Partly transparent points use continent colors and shapes.

alpha = 0.7

Alpha controls opacity on a zero-to-one scale. Seventy percent opacity is 0.7. Each of the 1,704 points is a country-year record; transparency helps reveal overlap. It does not combine observations or change their coordinates.

Question 19

2 points · Lecture 8

Complete the fitted trend for the United States.

us_history <- gapminder |>
  filter(country == "United States")

ggplot(data = us_history,
       mapping = aes(x = gdpPercap,
                     y = lifeExp)) +
  geom_point(alpha = 0.7,
             color = "steelblue") +
  geom_smooth(method = [?],
              se = FALSE,
              color = "grey30") +
  labs(x = "United States GDP per person (US$)",
       y = "United States life expectancy (years)")

Target visualization:

The United States’ 12 observations from 1952 to 2007 appear as blue points on GDP-per-person and life-expectancy axes, with one upward straight fitted line and no ribbon.

"lm"

The method string “lm” requests the straight linear-regression fit shown. Each point is one of the United States’ 12 recorded years from 1952 to 2007, rather than a different country. The line summarizes their association; it does not show that GDP alone caused the changes in life expectancy.

Question 20

2 points · Lecture 8

Match the target’s treatment of uncertainty.

us_canada_history <- gapminder |>
  filter(country == "United States" |
         country == "Canada")

ggplot(data = us_canada_history,
       mapping = aes(x = year,
                     y = log10(gdpPercap),
                     color = country,
                     linetype = country)) +
  geom_point(mapping = aes(shape = country),
             size = 2) +
  geom_smooth(se = [?]) +
  scale_color_colorblind() +
  labs(x = "Year of record",
       y = "log10(GDP per person)",
       color = "Country",
       linetype = "Country",
       shape = "Country")

Target visualization:

The United States and Canada have separate smooth fitted log-GDP trends over 1952–2007, with their observed points and no shaded uncertainty ribbons. Colors, shapes, and line types identify the two countries.

FALSE

se = FALSE hides the fitted curves’ uncertainty ribbons. The two curves use the 12 observations for the United States and the 12 for Canada. Omitting method lets geom_smooth() use its default fitting method. This display choice does not eliminate statistical uncertainty or change the data.

Question 21

3 points · Lecture 8

Reproduce the horizontal scale shown in the target.

ggplot(data = countries_2007,
       mapping = aes(x = [?],
                     y = lifeExp,
                     color = continent,
                     shape = continent)) +
  geom_point(alpha = 0.85,
             size = 2) +
  scale_color_colorblind() +
  labs(x = "log10(GDP per person in US$)",
       y = "Life expectancy (years)",
       color = "Continent",
       shape = "Continent")

Target visualization:

Life expectancy plotted against log10 GDP per person for 142 countries. Colors and point shapes identify continents, and lower-GDP countries are more spread out horizontally than on an ordinary dollar axis.

log10(gdpPercap)

Putting log10(gdpPercap) inside aes() calculates the horizontal positions from the original positive GDP values. It gives equal horizontal spacing to equal proportional changes. The original gdpPercap column remains available in dollars, and life expectancy remains in years.

Question 22

2 points · Lecture 8

Reproduce these three countries’ trends and their uncertainty bands.

north_america_history <- gapminder |>
  filter(country == "United States" |
         country == "Canada" |
         country == "Mexico")

ggplot(data = north_america_history,
       mapping = aes(x = year,
                     y = lifeExp,
                     color = country,
                     fill = [?],
                     linetype = country)) +
  geom_smooth(alpha = 0.15,
              linewidth = 1) +
  scale_color_tableau() +
  scale_fill_tableau() +
  labs(x = "Year of record",
       y = "Life expectancy (years)",
       color = "Country",
       fill = "Country",
       linetype = "Country")

Target visualization:

Three life-expectancy curves extend from 1952 to 2007 for Canada, Mexico, and the United States. Distinct colors and line types identify countries, with lightly shaded confidence bands matching each curve. Mexico starts much lower and rises more rapidly, while Canada and the United States begin higher.

country

The fill aesthetic controls the interiors of the uncertainty bands. Mapping fill to country makes each band correspond to its country’s fitted line; color and line type already distinguish the three fits. The plot uses 12 country-year records for each of the United States, Canada, and Mexico. It does not combine their residents into a single North American life expectancy.

Question 23

3 points · Lecture 8

Arrange the comparisons for the three years as shown.

comparison_years <- gapminder |>
  filter(year == 1952 |
         year == 1977 |
         year == 2007)

ggplot(data = comparison_years,
       mapping = aes(x = log10(gdpPercap),
                     y = lifeExp)) +
  geom_point(mapping = aes(color = continent,
                           shape = continent),
             alpha = 0.45,
             size = 1.7) +
  geom_smooth(method = "lm",
              se = FALSE,
              color = "grey25") +
  [?] +
  scale_color_colorblind() +
  labs(x = "log10(GDP per person)",
       y = "Life expectancy (years)",
       color = "Continent",
       shape = "Continent")

Target visualization:

Three panels labeled 1952, 1977, and 2007 compare life expectancy against base-10 log GDP per person. Continent-colored and shaped country points surround one dark straight fitted line in each panel; the panels share axis scales.

facet_wrap(~ year)

Faceting by year creates the 1952, 1977, and 2007 panels. Each panel contains 142 country records and has its own pooled straight fit. Continent color and shape belong only to the point layer, so they do not split the fitted line into separate continent models. Shared axes support comparisons across the three snapshots.

Question 24

3 points · Lecture 8

Complete the historical GDP series for the United States.

us_economy <- gapminder |>
  filter(country == "United States")

ggplot(data = us_economy,
       mapping = [?]) +
  geom_line(color = "steelblue",
            linewidth = 0.8) +
  geom_point(color = "steelblue",
             size = 2) +
  labs(x = "Year of record",
       y = "United States GDP per person (US$)")

Target visualization:

The United States’ GDP per person from 1952 through 2007, shown as blue points joined in year order on an ordinary dollar axis. GDP per person increases across the recorded observation dates.

aes(x = year,
    y = gdpPercap)

Year controls horizontal position and gdpPercap controls the vertical position. The plot connects the United States’ 12 recorded GDP-per-person values in year order. The vertical axis uses the original dollar units, not logarithms.

Question 25

4 points · Lecture 8

Plot the 2007 country records from the Americas or Europe with life expectancy at least 70 years, including the United States.

selected_countries <- three_continents |>
  filter([?])

ggplot(data = selected_countries,
       mapping = aes(x = log10(gdpPercap),
                     y = lifeExp,
                     color = continent,
                     shape = continent)) +
  geom_point(alpha = 0.65,
             size = 2) +
  geom_smooth(method = "lm",
              se = FALSE) +
  scale_color_colorblind() +
  labs(x = "log10(GDP per person in US$)",
       y = "Life expectancy (years)",
       color = "Continent",
       shape = "Continent")

Target visualization:

Log10 GDP and life expectancy for countries in the Americas and Europe with life expectancy at least 70 years in 2007, including the United States. Colors and shapes distinguish the two continents, and each has a separate straight fitted line.

(continent == "Americas" |
 continent == "Europe") &
lifeExp >= 70

The parentheses combine the two allowed continents first. The AND condition then requires life expectancy of at least 70 for either continent. The selected records include the United States. Each continent has its own fitted line.

Question 26

4 points · Lecture 8

Complete the country histories and continental trends shown.

ggplot(data = gapminder,
       mapping = [?]) +
  geom_line(mapping = aes(group = country),
            color = "grey70",
            linewidth = 0.3,
            alpha = 0.45,
            show.legend = FALSE) +
  geom_smooth(se = FALSE,
              linewidth = 1.1,
              show.legend = FALSE) +
  facet_wrap(~ continent) +
  scale_color_colorblind() +
  labs(x = "Year of record",
       y = "log10(GDP per person)",
       color = "Continent")

Target visualization:

Five labeled continent panels show thin grey country GDP histories from 1952 to 2007 on a base-10 logarithmic vertical axis. Each panel also has one thicker colored smooth curve without an uncertainty ribbon, and the panels share axis scales.

aes(x = year,
    y = log10(gdpPercap),
    color = continent)

Year controls horizontal position and log10(gdpPercap) controls vertical position. The color mapping gives the smooth layer its continent groups. The supplied country grouping applies only to the thin grey line layer, keeping each country history intact without creating a separate smooth for every country. Each panel therefore shows country trajectories and one continental trend in the plotted log-GDP values. These are descriptive patterns in the dataset, not causal effects.

Question 27

4 points · Lecture 8

Add the overall fitted trend for the Americas, Asia, and Europe, including the United States.

ggplot(data = three_continents,
       mapping = aes(x = log10(gdpPercap),
                     y = lifeExp)) +
  geom_point(mapping = aes(color = continent,
                           shape = continent),
             alpha = 0.55,
             size = 2) +
  [?] +
  scale_color_colorblind() +
  labs(x = "log10(GDP per person)",
       y = "Life expectancy (years)",
       color = "Continent",
       shape = "Continent")

Target visualization:

the Americas, Asia, and Europe appear as differently colored and shaped country points, with one overall straight fitted line across all 88 observations and no ribbon.

geom_smooth(method = "lm",
            se = FALSE)

This layer adds one straight fit with no uncertainty ribbon. The continent mappings belong to the point layer, so the added fit uses all 88 country records together. Putting continent in the global mapping would instead produce separate group fits.

Question 28

4 points · Lecture 8

Reproduce the population–GDP relationship for the three continents, including the United States.

ggplot(data = three_continents,
       mapping = [?]) +
  geom_point(mapping = aes(color = continent,
                           shape = continent),
             alpha = 0.65,
             size = 2) +
  geom_smooth() +
  scale_color_colorblind() +
  labs(x = "log10(GDP per person)",
       y = "log10(Population in people)",
       color = "Continent",
       shape = "Continent")

Target visualization:

Population versus GDP per person for the Americas, Asia, and Europe in 2007, with base-10 logarithms on both axes. Color and point shape identify continents; each point represents a country. One fitted smooth curve and its confidence ribbon summarize the overall relationship.

aes(x = log10(gdpPercap),
    y = log10(pop))

Both axes use transformed values: log10(gdpPercap) determines horizontal position and log10(pop) determines vertical position. All GDP and population values in this subset are positive. Equal multiplicative changes receive equal spacing on either log axis. The plot still has one point per country, and the original columns remain available. The supplied geom_smooth() layer adds one overall fitted curve with its default confidence ribbon. Continent is mapped only in the point layer, so it does not split this curve by continent.

Question 29

4 points · Lecture 8

Keep the United States and India from 1982 through 2007, inclusive, then reproduce the population trends.

selected_population <- gapminder |>
  filter([?])

ggplot(data = selected_population,
       mapping = aes(x = year,
                     y = pop / 1000000,
                     color = country,
                     linetype = country)) +
  geom_line(linewidth = 1) +
  geom_point(mapping = aes(shape = country),
             size = 2) +
  scale_color_colorblind() +
  labs(x = "Year of record",
       y = "Population (millions of people)",
       color = "Country",
       linetype = "Country",
       shape = "Country")

Target visualization:

The United States and India population histories from 1982 through 2007, with six points per country, connected by separate colored and patterned lines. Population is measured in millions of people. India has the larger population throughout this interval.

(country == "United States" |
 country == "India") &
year >= 1982 &
year <= 2007

The parenthesized country condition admits either the United States or India, and both year bounds apply to either country. There are six recorded years per country: 1982, 1987, 1992, 1997, 2002, and 2007. The supplied division displays population in millions.

Question 30

4 points · Lecture 8

Reproduce these GDP histories.

gdp_histories <- gapminder |>
  filter(country == "Kuwait" |
         country == "United States" |
         country == "Japan")

ggplot(data = gdp_histories,
       mapping = [?]) +
  geom_line(linewidth = 1) +
  geom_point(mapping = aes(shape = country),
             size = 2) +
  scale_color_colorblind() +
  labs(x = "Year of record",
       y = "log10(GDP per person)",
       color = "Country",
       linetype = "Country",
       shape = "Country")

Target visualization:

The United States, Japan, and Kuwait have separate colored and patterned GDP histories from 1952 to 2007, with symbols at the 12 recorded years. The vertical axis is base-10 log GDP per person. Kuwait starts high and fluctuates markedly; United States GDP per person rises throughout the recorded years, and Japan rises rapidly before its growth slows.

aes(x = year,
    y = log10(gdpPercap),
    color = country,
    linetype = country)

The mapping places recorded years horizontally and base-10 log GDP per person vertically. Mapping country to color and line type separates the histories for the United States, Japan, and Kuwait; the supplied point layer adds country-specific symbols. Kuwait’s fluctuations differ from the rising United States and Japan histories. The logarithmic axis compares multiplicative differences in GDP per person, and each country contributes 12 recorded years.

Question 31

3 points · Lecture 8

Reproduce the population histories in the three panels.

population_histories <- gapminder |>
  filter(country == "United States" |
         country == "Germany" |
         country == "Japan")

ggplot(data = population_histories,
       mapping = [?]) +
  geom_line(mapping = aes(color = country),
            linewidth = 0.8,
            show.legend = FALSE) +
  geom_point(mapping = aes(color = country),
             size = 1.6,
             show.legend = FALSE) +
  facet_wrap(~ country) +
  scale_color_colorblind() +
  labs(x = "Year of record",
       y = "log10(Population in people)")

Target visualization:

Three panels labeled Germany, Japan, and United States show population histories from 1952 to 2007. Colored lines connect each country’s 12 observations, the vertical axis is base-10 log population in people, and all panels share axis scales. The United States has the largest population throughout the period, while Germany’s changes are comparatively small.

aes(x = year,
    y = log10(pop))

The shared position mapping uses year and log10(pop). The supplied line and point layers identify country through color, and the facets separate the United States, Germany, and Japan. Each panel contains 12 country-year observations. Equal vertical distances represent equal population ratios rather than equal additions of people; the country labels and shared scales make the histories comparable.

Question 32

3 points · Lecture 8

Add the fitted trends shown for the United States and South Africa.

life_histories <- gapminder |>
  filter(country == "United States" |
         country == "South Africa")

ggplot(data = life_histories,
       mapping = aes(x = year,
                     y = lifeExp,
                     color = country,
                     fill = country,
                     linetype = country)) +
  geom_line(linewidth = 0.7,
            alpha = 0.45) +
  geom_point(mapping = aes(shape = country),
             size = 2) +
  [?] +
  scale_color_tableau() +
  scale_fill_tableau() +
  labs(x = "Year of record",
       y = "Life expectancy (years)",
       color = "Country",
       fill = "Country",
       linetype = "Country",
       shape = "Country")

Target visualization:

United States and South Africa life-expectancy observations from 1952 to 2007 appear as country-specific points joined by faint lines. Separate fitted smooth curves have matching shaded confidence ribbons. The United States rises gradually from about 68 to 78 years; South Africa rises from about 45 to the low 60s before declining to about 49 years.

geom_smooth()

geom_smooth() adds an estimated-average curve with its default confidence ribbon for each country. The inherited country mappings keep the two fitted trends separate. The existing lines connect observed values, and the point symbols identify recorded years. United States life expectancy rises through the period, while South Africa’s rise is followed by a decline. These historical patterns do not establish their causes or predict later outcomes.

Back to top