đ Introduction
ggplot2 is one of the most powerful and widely used data visualization packages in R. It is part of the tidyverse and is based on the Grammar of Graphics, a system that builds plots by combining layers such as data, aesthetics, geometries, scales, labels, and themes. With ggplot2, you can create professional, attractive, and highly customizable visualizations.
Information
đ¯ Why Learn ggplot2?
- Create publication-quality graphics.
- Build complex visualizations using simple syntax.
- Customize every aspect of a chart.
- Integrate seamlessly with tidyverse packages.
- Visualize data efficiently for analysis and reporting.
đĻ Installing and Loading ggplot2
Install the package once and load it whenever you want to create visualizations.
Install and Load ggplot2
install.packages("ggplot2")
library(ggplot2)đ§ą Grammar of Graphics
đ Basic Structure of a ggplot
Every ggplot2 visualization begins with the ggplot() function, followed by one or more layers.
Basic ggplot Syntax
ggplot(
data,
aes(
x = variable1,
y = variable2
)
) +
geom_point()đ Creating a Sample Dataset
Sample Data
library(ggplot2)
students <- data.frame(
Name = c(
"Alice",
"Bob",
"Charlie",
"David"
),
Marks = c(
85,
72,
91,
78
),
Age = c(
20,
21,
20,
22
)
)
print(students)đ Creating a Scatter Plot
The geom_point() layer creates a scatter plot.
Scatter Plot
ggplot(
students,
aes(
x = Age,
y = Marks
)
) +
geom_point()đ Creating a Line Chart
The geom_line() layer connects observations with lines.
Line Chart
sales <- data.frame(
Month = 1:6,
Sales = c(
120,
150,
180,
170,
210,
230
)
)
ggplot(
sales,
aes(
x = Month,
y = Sales
)
) +
geom_line()đ Creating a Bar Chart
The geom_col() layer creates bar charts using supplied values.
Bar Chart
ggplot(
students,
aes(
x = Name,
y = Marks
)
) +
geom_col()đĻ Creating a Histogram
The geom_histogram() layer displays the distribution of numerical data.
Histogram
ggplot(
students,
aes(
x = Marks
)
) +
geom_histogram(
bins = 5
)đ Creating a Box Plot
Box plots summarize data distributions and help identify outliers.
Box Plot
ggplot(
students,
aes(
x = "",
y = Marks
)
) +
geom_boxplot()đ¨ Adding Colors
Colors can be assigned directly or mapped to variables using the color and fill aesthetics.
Colored Scatter Plot
ggplot(
students,
aes(
x = Age,
y = Marks
)
) +
geom_point(
color = "blue",
size = 4
)đ Mapping Colors to Categories
Color by Category
students$Department <- c(
"IT",
"CS",
"IT",
"AI"
)
ggplot(
students,
aes(
x = Age,
y = Marks,
color = Department
)
) +
geom_point(size = 4)đ Adding Titles and Labels
The labs() function adds titles and axis labels.
Labels
ggplot(
students,
aes(
x = Age,
y = Marks
)
) +
geom_point() +
labs(
title = "Student Performance",
x = "Age",
y = "Marks"
)đ Applying Themes
Themes control the overall appearance of a plot.
Using Themes
ggplot(
students,
aes(
x = Age,
y = Marks
)
) +
geom_point() +
theme_minimal()Popular Themes
| Theme | Description |
|---|---|
| theme_gray() | Default ggplot2 theme. |
| theme_bw() | Black-and-white theme. |
| theme_classic() | Classic appearance. |
| theme_minimal() | Clean and minimal design. |
| theme_light() | Light background. |
đ Faceting
Faceting creates multiple plots based on the values of a categorical variable.
Using facet_wrap()
ggplot(
students,
aes(
x = Age,
y = Marks
)
) +
geom_point() +
facet_wrap(
~ Department
)đ Combining Multiple Layers
Multiple geometric layers can be added to the same plot.
Multiple Layers
ggplot(
sales,
aes(
x = Month,
y = Sales
)
) +
geom_line(
color = "blue"
) +
geom_point(
color = "red",
size = 3
)đž Saving a Plot
The ggsave() function saves the most recently created plot.
Saving a Plot
plot <- ggplot(
students,
aes(
x = Age,
y = Marks
)
) +
geom_point()
ggsave(
"students_plot.png",
plot = plot,
width = 6,
height = 4
)đ Real-World Example
A company wants to visualize monthly sales using a professional line chart.
Monthly Sales Visualization
sales <- data.frame(
Month = c(
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun"
),
Sales = c(
12000,
13500,
15000,
14800,
17000,
18200
)
)
ggplot(
sales,
aes(
x = Month,
y = Sales,
group = 1
)
) +
geom_line(
color = "darkgreen",
linewidth = 1.2
) +
geom_point(
color = "red",
size = 3
) +
labs(
title = "Monthly Sales Report",
x = "Month",
y = "Sales"
) +
theme_minimal()đ ggplot2 Workflow
đ Common Geometric Layers
| Geometry | Purpose |
|---|---|
| geom_point() | Scatter plots. |
| geom_line() | Line charts. |
| geom_col() | Bar charts using supplied values. |
| geom_bar() | Bar charts using counts. |
| geom_histogram() | Histograms. |
| geom_boxplot() | Box plots. |
| geom_smooth() | Trend or regression lines. |
| geom_text() | Adds text labels. |
â ī¸ Common Mistakes
| Mistake | Explanation | Solution |
|---|---|---|
| Forgetting to load ggplot2 | The ggplot() function will not be available. | Run library(ggplot2) before creating plots. |
| Using incorrect aesthetic mappings | Variables may not display correctly. | Place variable mappings inside aes(). |
| Using geom_line() without grouping | Lines may not connect as expected for categorical x-values. | Specify group = 1 or an appropriate grouping variable. |
| Confusing mapped aesthetics with fixed values | Colors and sizes may behave unexpectedly. | Use aes() for variable mappings and specify fixed values outside aes(). |
đĄ Best Practices
- Build plots layer by layer using the + operator.
- Use meaningful titles, axis labels, and legends.
- Choose chart types that match the data.
- Apply clean themes such as theme_minimal() or theme_classic().
- Keep visualizations simple, consistent, and easy to interpret.
Best Practice
đ Summary
ggplot2 is a powerful visualization package based on the Grammar of Graphics. You learned how to create scatter plots, line charts, bar charts, histograms, and box plots, customize aesthetics, apply themes, use faceting, combine multiple layers, and save plots. Mastering these fundamentals provides a strong foundation for creating informative, attractive, and publication-quality data visualizations in R.