Lecture 8

Data Visualization II: Relationships and Time Trends

Byeong-Hak Choe

SUNY Geneseo

November 1, 2026

🔗 Relationships between variables

🧩 The same grammar supports a new question

  • We have used data, mappings in aes(), and a geom layer to show distributions and compare groups.
  • Now the question is: How is engine size related to highway fuel economy?
  • A scatterplot maps two numeric variables to horizontal and vertical positions.
Part of the plot What stays familiar What changes here
data = mpg The data frame We keep the same vehicle rows
mapping = aes(...) Variables control visual features Both x and y contain numeric variables
geom_*() A layer draws the data geom_point() draws a point for each row

🔵 A scatterplot places each row using two values

ggplot(data = mpg,
       mapping = aes(x = displ,
                     y = hwy)) +
  geom_point() +
  labs(
    x = "Engine size (liters)",
    y = "Highway fuel economy (mpg)"
  )

Scatterplot of engine size in liters and highway fuel economy in miles per gallon. Larger engines generally accompany lower highway fuel economy.

  • x-axis (input): engine size (displ, liters), used to explain or predict the outcome.
  • y-axis (outcome): highway fuel economy (hwy, miles per gallon), the value we want to understand.
  • Vehicles with the same engine size and highway mpg overlap, so a visible dot may represent multiple vehicle records.

👀 Direction, variation, and unusual points

A fitted straight line summarizes the downward association between engine size and highway fuel economy.

A translucent blue vertical box highlights different highway mpg values among vehicles with similar engine sizes.

A translucent red box highlights vehicles with relatively high highway mpg for their large engines.

  • Direction: larger engines generally accompany lower highway mpg. This is a negative association.
  • Variation: vehicles with similar engine sizes can have different highway mpg.
  • Unusual points: the red box highlights relatively high highway mpg for large engines. Look closer at those rows and their context.

↗️ Positive, negative, or no clear relationship?

Positive

A scatterplot with an upward fitted line: higher x tends to go with higher y.

Higher x tends to go with higher y.

Negative

A scatterplot with a downward fitted line: higher x tends to go with lower y.

Higher x tends to go with lower y.

No clear relationship

Points form a cloud with no clear relationship and a nearly flat fitted line.

As x increases, y shows no clear upward or downward pattern.

📉 A smooth curve summarizes the relationship

ggplot(data = mpg,
       mapping = aes(x = displ,
                     y = hwy)) +
  geom_point() +
  geom_smooth() +
  labs(
    x = "Engine size (liters)",
    y = "Highway fuel economy (mpg)"
  )

Engine size and highway mpg scatterplot with the default smooth curve and its shaded uncertainty ribbon.

  • One ggplot can contain both geom_point() and geom_smooth().
  • Using regression, which is one of the machine learning methods, geom_smooth() shows the predicted average y for a given x.

📏 Use a straight line with method = "lm"

ggplot(data = mpg,
       mapping = aes(x = displ,
                     y = hwy)) +
  geom_point() +
  geom_smooth(method = "lm") +
  labs(
    x = "Engine size (liters)",
    y = "Highway fuel economy (mpg)"
  )

The same scatterplot with a fitted straight line and a shaded confidence ribbon.

  • geom_smooth(method = "lm") specifies that a linear model (lm), called a linear regression model
    • This fits a straight line.
  • At a given engine size (x), the line gives an estimated average highway mpg (y) based on these data.

🧹 Hide the ribbon with se = FALSE

ggplot(data = mpg,
       mapping = aes(x = displ,
                     y = hwy)) +
  geom_point() +
  geom_smooth(
    method = "lm", 
    se = FALSE) +  # se: standard error
  labs(
    x = "Engine size (liters)",
    y = "Highway fuel economy (mpg)")

The same fitted straight line with the shaded uncertainty ribbon hidden.

  • se = FALSE hides the shaded ribbon around the fitted line.
  • The grey ribbon represents uncertainty around that estimated average.
    • At each x it gives a 95% confidence interval for the average y.
    • We are 95% confident that the actual relationship between x and y variables falls within the grey ribbon.

–>

⚠️ Correlation does not imply causation

Correlation

Ice cream sales and shark attacks illustrated with a cone and a shark.
Both can increase in summer

Two variables tend to vary together.

Causation

An arrow connects someone pushing a cart to the cart moving.
The push causes the movement

A change in one variable helps produce a change in the other.

A scatterplot can show an association, but it cannot tell us whether one variable causes changes in the other.

🎨 Mapped color identifies groups

library(ggthemes)

ggplot(data = mpg,
       mapping = aes(x = displ,
                     y = hwy,
                     color = drv)) +
  geom_point(alpha = 0.5) +
  geom_smooth() +
  scale_color_tableau() +
  labs(
    x = "Engine size (liters)",
    y = "Highway fuel economy (mpg)",
    color = "Drive system"
  )

Scatterplot of engine size and highway mpg. Point color identifies drive system, and semitransparency helps reveal overlapping observations.

  • color = drv inside aes() maps groups to colors. scale_color_tableau() chooses those colors.
  • alpha ranges from 0 (invisible) to 1 (fully opaque). At alpha = 0.5, points are partly transparent, so overlaps appear darker.

🔺 Mapped shape also identifies groups

ggplot(data = mpg,
       mapping = aes(x = displ,
                     y = hwy,
                     color = drv,
                     shape = drv)) +
  geom_point(size = 2.5) +
  geom_smooth() +
  scale_color_tableau() +
  labs(x = "Engine size (liters)",
       y = "Highway fuel economy (mpg)",
       color = "Drive system",
       shape = "Drive system")

Scatterplot of engine size and highway mpg with both point shape and color identifying the drive system.

  • shape = drv inside aes() gives each drive-system group a different point symbol.
    • shape applies to geom_point(), not geom_smooth().
  • Using shape and color together gives viewers two ways to identify the groups.

━ Mapped linetype also identifies groups

ggplot(data = mpg,
       mapping = aes(x = displ,
                     y = hwy,
                     color = drv,
                     fill = drv,
                     linetype = drv)) +
  geom_smooth() +
  scale_color_tableau() +
  scale_fill_tableau() +
  labs(x = "Engine size (liters)",
       y = "Highway fuel economy (mpg)",
       color = "Drive system",
       fill = "Drive system",
       linetype = "Drive system")

Scatterplot of engine size and highway mpg with both linetype and color identifying the drive system.

  • linetype = drv inside aes() gives each drive-system group a different line.
    • linetype applies to geom_smooth(), not geom_point().
    • fill controls the color of the ribbon for geom_smooth().

🖌️ Mappings and fixed appearances

ggplot(data = mpg,
       mapping = aes(x = displ,
                     y = hwy)) +
  geom_point(color = "steelblue", 
             alpha = 0.5)

Scatterplot with every point drawn in the same partly transparent steel-blue color, set outside aes().

Code Meaning
aes(color = drv) Let a variable determine each point’s color
geom_point(color = "steelblue") Give every point the same chosen color
  • A variable belongs inside aes() when its values should control a visual feature.
  • A fixed appearance belongs outside aes(). A color name inside aes() can create an unintended legend.

🪟 Facets separate the groups

ggplot(data = mpg,
       mapping = aes(x = displ,
                     y = hwy)) +
  geom_point(alpha = 0.4) +
  geom_smooth(method = "lm", se = FALSE) +
  facet_wrap(~ drv)

Three scatterplot panels compare engine size and highway mpg within drive systems, each with its own fitted straight line. All panels share the same axis scales.

  • Both colors and facets can be used to show how the relationship between two numeric variables differs across groups.

✍️ Classwork 14: Relationships

  • Plot age and recorded income for selected New York customers. Compare a smooth curve and a fitted straight line in Questions 1–2.
  • Questions 3–4 use color and shape to identify three housing types and distinguish mappings from fixed settings.
  • In Question 5, compare the smooth curves in separate housing panels with shared axes.

🌍 Log transformations and relationships

🌍 Historical country data

Country GDP per person Life expectancy
Afghanistan 974.6 43.8
Albania 5937.0 76.4
Algeria 6223.4 72.3
Angola 4797.2 42.7
  • Each row represents one country in 2007, with 142 countries in this dataset.
  • gdpPercap is GDP per person in inflation-adjusted dollars, a measure of economic output per person.
  • lifeExp is life expectancy at birth in years.

📥 Importing the country data

gapminder_2007 <- read_csv(
  "https://bcdanl.github.io/data/gapminder.csv"
) |>
  filter(year == 2007)
  • read_csv() imports the CSV file as a data frame in R.
  • filter(year == 2007) keeps a single year of 2007, so each country contributes one observation.

🧮 Log transformations emphasize relative differences

An ordinary dollar number line labeled $1,000, $2,000, $4,000, and $8,000. The +100% steps have increasingly wide gaps.

A base-10 logarithmic number line with equal-length +100% steps. Below the dollar labels $1,000, $2,000, $4,000, and $8,000 are their rounded log10 values: 3.00, 3.30, 3.60, and 3.90.

  • An ordinary dollar scale uses equal distances for equal dollar differences.
  • A log scale uses equal distances for equal percentage changes: each step here doubles GDP per person (+100%).

📊 A log transformation changes the spacing

Original GDP

Histogram of original GDP per person in 2007, with many countries at the lower end and a long right tail.

mapping = aes(x = gdpPercap)

Logged GDP

Histogram of base-10 log GDP per person for the same 142 countries, with more space between lower-GDP values and a compressed upper tail.

mapping = aes(x = log10(gdpPercap))
  • The original GDP values are right-skewed: many countries have lower values, with a few much higher values.
  • Logging compresses the high end and makes differences among lower values easier to see.

🌍 GDP and life expectancy on two scales

Original GDP

Scatterplot of life expectancy against original GDP per person in 2007 with a fitted straight line. Many lower-GDP countries crowd together on the left.

Logged GDP

Scatterplot of life expectancy against base-10 log GDP per person with a fitted straight line, making differences among lower-GDP countries easier to distinguish.

  • Higher GDP per person generally accompanies higher life expectancy in these observations.
  • The log axis makes lower-GDP countries easier to distinguish. Life expectancy stays in years in both plots.

🧩 A transformation can go inside aes()

ggplot(data = gapminder_2007,
       mapping= aes(x = log10(gdpPercap),
                    y = lifeExp)) +
  geom_point() +
  geom_smooth(method = lm)

Life expectancy plotted against log10 GDP per person, with a fitted straight line and confidence ribbon.

  • log10(gdpPercap) calculates the horizontal positions from the GDP values.
  • lifeExp stays in its original units: years.
  • The plot uses transformed positions without replacing the original gdpPercap column.

✍️ Classwork 15: Log transformations

  • Draw histograms of recorded income and log10(income) in ny_customers. Then plot each against age with a default smooth curve and a fitted straight line.
  • Explain why each doubling takes the same vertical distance on the log-income scatterplot.

🗓️ Stock-price rows identify a company and a date

Date Company ticker Closing price (US$)
2026-10-01 AAPL 330.32
2026-10-01 NVDA 230.86
2026-10-02 AAPL 333.69
2026-10-02 NVDA 233.95
  • Each row represents one company on one trading day in October 2026.
  • AAPL identifies Apple, and NVDA identifies NVIDIA. Close gives the closing price per share in US dollars.
  • A line chart lets us follow these observations in chronological order.

🗓️ Preparing dates and selecting companies

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

tech_two <- tech_october |>
  filter(Ticker == "AAPL" | Ticker == "NVDA")

apple_october <- tech_two |>
  filter(Ticker == "AAPL")
  
msft_october <- tech_october |>
  filter(Ticker == "MSFT")
  
msft_2026 <- read_csv(
  "https://bcdanl.github.io/data/msft_2026.csv"
)
  • read_csv() may already recognize a column such as "2026-10-01" as the Date type.

📈 Points and a line show one company’s history

ggplot(data = apple_october,
       mapping = aes(x = Date,
                     y = Close)) +
  geom_line(color = "steelblue") +
  geom_point(color = "steelblue") +
  labs(
    x = "Date in October 2026",
    y = "Closing price (US$/share)"
  )

Points and a line show Apple's closing share price across trading days in October 2026, connecting observations in date order.

  • geom_point() marks the observed values. geom_line() connects them in x-axis order.
  • The file contains trading days. A connecting segment does not provide an observed closing price for every calendar day.

📉 A smooth curve shows the broader movement

ggplot(data = msft_2026,
       mapping = aes(
         x = Date,
         y = AdjustedClose)) +
  geom_line(color = "grey70") +
  geom_point(
    color = "steelblue", size = 0.6) +
  geom_smooth() +
  labs(x = "Date in 2026",
       y = "Adjusted close ($/share)")

Microsoft's daily adjusted closing prices from January through September 2026. A thin grey line and small points show daily changes, while a smooth blue curve summarizes the broader movement across nine months.

  • msft_2026 contains 187 trading days from January–September 2026. The points and line show day-to-day price changes.
  • geom_smooth() adds an predicted average trend by smoothing out variability in the observations.

⚠️ One line mixes the two companies

# Incorrect grouping
ggplot(data = tech_two,
       mapping = aes(x = Date,
                     y = Close)) +
  geom_point(color = "steelblue") +
  geom_line(color = "grey60") +
  labs(
    x = "Date",
    y = "Closing price (US$/share)"
  )

Incorrect plot joins Apple and NVIDIA prices as a single series, creating artificial jumps between companies on the same dates.

  • The combined data have two observations on each date, one per company.
  • This code connects the observations as one group, producing jumps between unrelated company prices.

🧵 Mapped color separates the company lines

ggplot(data = tech_two,
       mapping = aes(x = Date,
                     y = Close,
                     color = Ticker,
                     linetype = Ticker)) +
  geom_line(linewidth = 1) +
  scale_color_colorblind() +
  labs(
    x = "Date",
    y = "Closing price (US$/share)",
    color = "Company",
    linetype = "Company")

Separate Apple and NVIDIA price lines over October 2026. Both color and line type distinguish the companies.

  • Mapping the categorical Ticker variable to color creates a separate line for each company.
  • linetype = Ticker also distinguishes the companies when colors are hard to tell apart.

🌐 Local mappings apply to one layer

ggplot(data = tech_october,
       mapping = aes(x = Date,
                     y = Close)) +
  geom_line(
    mapping = aes(color = Ticker)) +
  geom_point() +
  scale_color_colorblind()

October 2026 closing prices from tech_october. Company-specific colors distinguish the four lines, while all observed points use the same default color.

  • Global aes() in ggplot() supplies x = Date and y = Close to both layers.
  • Local aes() in geom_line() maps color = Ticker for the lines. geom_point() uses the shared positions and a single default color.

🧭 Questions, variables, and ggplot layers

Question Variables Useful layer
How are values distributed? One numeric variable geom_histogram()
How do distributions differ across groups? Numeric + category geom_boxplot()
How do categories compare? Category counts or supplied values geom_bar() or geom_col()
How do variables vary together? Two numeric variables geom_point() + geom_smooth()
How does a quantity change through time? Date + numeric variable geom_line()
  • Start with the question: choose the variables, map them in aes(), and add the geom layers that show the comparison you need.

✍️ Classwork 16: Visualizing Time Trends

  • Plot Microsoft’s October 2026 trading volume using points, a line, and a smooth curve.
  • Compare Microsoft and Meta on shared axes. Use color and line type to distinguish the companies.