Consider the following R code using ggplot2. What will be the main visual element shown?
library(ggplot2) data <- data.frame(x = 1:5, y = c(3, 5, 2, 8, 7)) ggplot(data, aes(x = x, y = y)) + geom_point()
Look at the geom_point() function. It adds points to the plot.
The geom_point() function creates a scatter plot by placing points at the (x, y) coordinates specified in aes(). So the plot shows points at the given data coordinates.
Given the same data, what will this code produce?
library(ggplot2) data <- data.frame(x = 1:5, y = c(3, 5, 2, 8, 7)) ggplot(data, aes(x = y, y = x)) + geom_point()
Swapping x and y in aes() changes the axes.
Swapping x and y means the horizontal axis shows the original y values and the vertical axis shows the original x values. The points are plotted accordingly.
In ggplot2, how do you map the color of points to a variable group in the data?
Mapping aesthetics inside aes() links them to data variables.
To map color to a variable, you include color = group inside aes() in ggplot(). Option A also works by placing aes(color = group) inside geom_point() since aesthetics merge, but option C is the standard way using the global aes().
Look at this code snippet. Why does it cause an error?
library(ggplot2) data <- data.frame(x = 1:3, y = c(4, 5, 6)) ggplot(data, aes(x = x, y = y)) + geom_point(aes(color = z))
Check if all variables used in aes() exist in the data.
The error occurs because z is not a column in the data frame. ggplot2 cannot map color to a variable that does not exist.
Given this code, how many points will appear in the plot?
library(ggplot2) data <- data.frame(x = c(1, 2, 2, 3), y = c(4, 5, 5, 6)) ggplot(data, aes(x = x, y = y)) + geom_point()
ggplot2 plots all rows; duplicates are not removed automatically.
ggplot2 plots one point per row in the data frame. Duplicate points appear multiple times. So all 4 points, including duplicates, are plotted.