Introduction
We use ggplot() and aes() to make clear and colorful pictures from data. They help us see patterns and stories in numbers.
We use ggplot() and aes() to make clear and colorful pictures from data. They help us see patterns and stories in numbers.
ggplot(data = your_data, aes(x = x_variable, y = y_variable)) + geom_point()
ggplot() starts the picture and needs your data.
aes() sets which columns go on the x and y axes.
ggplot(data = mtcars, aes(x = wt, y = mpg)) + geom_point()
ggplot(data = mtcars, aes(x = factor(cyl), y = mpg)) + geom_boxplot()
ggplot(data = mtcars, aes(x = hp, y = mpg, color = factor(cyl))) + geom_point()
This program loads ggplot2, then makes and shows a scatter plot of car weight vs miles per gallon.
library(ggplot2) # Use mtcars data to plot weight vs mpg p <- ggplot(data = mtcars, aes(x = wt, y = mpg)) + geom_point() print(p)
You must load the ggplot2 package before using ggplot().
aes() can be inside ggplot() or inside each geom_ function.
Adding + geom_point() tells R to draw points on the plot.
ggplot() starts your plot and needs your data.
aes() tells which data columns go on x and y axes.
Use geom_ functions like geom_point() to draw shapes.
aes() function in ggplot()?aes()aes() function defines how data columns are linked to visual elements like axes or colors.aes() purposeaes().ggplot() using data frame df and mapping x to column age and y to column height?ggplot() syntaxggplot(data, aes(...)) + geom_* where data is first, then aes() inside ggplot.ggplot(df, aes(x = age, y = height)) + geom_point() matches the correct order and usage. The other options misuse argument order or place aes() outside ggplot().library(ggplot2) df <- data.frame(x = 1:3, y = c(4, 5, 6)) ggplot(df, aes(x = x, y = y)) + geom_point()
ggplot(mtcars, aes(x = mpg, y = hp)) geom_point()
ggplot() with data frame df that has columns time, score, and group. You want points colored by group. Which code correctly achieves this?ggplot(df, aes(x = time, y = score, color = group)) + geom_point() correctly maps color inside aes() in ggplot().ggplot(df, aes(x = time, y = score)) + geom_point(color = group) sets color outside aes(), causing an error.ggplot(df) + aes(x = time, y = score, color = group) + geom_point() incorrectly treats aes() as a layer.ggplot(df, geom_point(aes(x = time, y = score, color = group))) incorrectly nests geom_point() inside ggplot().Pass the test and this pattern moves unknown