0
0
R Programmingprogramming~5 mins

ggplot() and aes() basics in R Programming

Choose your learning style9 modes available
Introduction

We use ggplot() and aes() to make clear and colorful pictures from data. They help us see patterns and stories in numbers.

You want to show how two things relate, like height and weight.
You need to compare groups, like sales in different months.
You want to make a simple chart from a table of data.
You want to add colors or shapes to points to show more info.
Syntax
R Programming
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.

Examples
This makes a scatter plot of car weight vs miles per gallon.
R Programming
ggplot(data = mtcars, aes(x = wt, y = mpg)) + geom_point()
This shows boxplots of miles per gallon grouped by number of cylinders.
R Programming
ggplot(data = mtcars, aes(x = factor(cyl), y = mpg)) + geom_boxplot()
This adds color to points based on the number of cylinders.
R Programming
ggplot(data = mtcars, aes(x = hp, y = mpg, color = factor(cyl))) + geom_point()
Sample Program

This program loads ggplot2, then makes and shows a scatter plot of car weight vs miles per gallon.

R Programming
library(ggplot2)

# Use mtcars data to plot weight vs mpg
p <- ggplot(data = mtcars, aes(x = wt, y = mpg)) + geom_point()
print(p)
OutputSuccess
Important Notes

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.

Summary

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.