Consider the following R code using ggplot2. What will the plot display?
library(ggplot2) data <- data.frame(x = 1:5, y = c(3, 5, 2, 8, 7)) ggplot(data, aes(x = x, y = y)) + geom_line()
Think about what geom_line() does with x and y aesthetics.
geom_line() connects points in the order of the x variable, creating a line plot.
group aesthetic in geom_line()?In ggplot2, when plotting multiple lines with geom_line(), why is the group aesthetic important?
Think about what happens if ggplot doesn't know which points belong together.
The group aesthetic tells ggplot which points form a single line. Without it, lines may connect points from different groups incorrectly.
Examine this R code snippet:
library(ggplot2) data <- data.frame(time = 1:4, value = c(2, 4, 6, 8)) ggplot(data, aes(x = time, y = value)) + geom_line(color = 5)
What error or warning will this code produce?
Check what type of value color expects in geom_line().
The color argument expects a color name or hex code as a string, not a number. Passing 5 causes an error.
Given this data frame:
df <- data.frame(
time = rep(1:3, 2),
value = c(2, 3, 5, 1, 4, 6),
group = rep(c('A', 'B'), each = 3)
)Which ggplot2 code correctly plots lines for each group?
Think about how to show separate lines by group with color.
Option D uses color = group which also sets grouping automatically, producing separate colored lines for each group.
Given this data frame and plot code:
df <- data.frame(
day = rep(1:4, 3),
score = c(5, 6, 7, 8, 3, 4, 5, 6, 9, 10, 11, 12),
player = rep(c('X', 'Y', 'Z'), each = 4)
)
ggplot(df, aes(x = day, y = score, group = player)) + geom_line()How many separate lines will appear in the plot?
Count the unique groups defined by player.
There are 3 unique players, so 3 separate lines will be drawn.