đ Introduction
While the fundamentals of ggplot2 focus on creating basic visualizations, Advanced ggplot2 introduces powerful techniques for building highly customized, publication-quality graphics. These techniques include aesthetic mappings, statistical transformations, multiple geometric layers, scales, themes, annotations, faceting, coordinate systems, and advanced customization.
Information
đ¯ Why Learn Advanced ggplot2?
- Create professional-quality visualizations.
- Customize every aspect of a chart.
- Visualize complex datasets effectively.
- Build reusable plotting workflows.
- Prepare graphics for research papers and business reports.
đĻ Loading Required Package
Load ggplot2
library(ggplot2)đ Sample Dataset
Employee Dataset
employees <- data.frame(
Name = c(
"Alice",
"Bob",
"Charlie",
"David",
"Emma",
"Frank"
),
Department = c(
"IT",
"HR",
"IT",
"Finance",
"HR",
"Finance"
),
Experience = c(
2,
5,
4,
6,
3,
8
),
Salary = c(
50000,
65000,
62000,
72000,
58000,
81000
)
)đ¨ Aesthetic Mappings
Multiple variables can be mapped to aesthetics such as color, size, shape, and transparency.
Multiple Aesthetic Mappings
ggplot(
employees,
aes(
x = Experience,
y = Salary,
color = Department,
size = Salary,
shape = Department
)
) +
geom_point()đ Adding Multiple Layers
Multiple geometric layers can be combined to create more informative visualizations.
Points and Trend Line
ggplot(
employees,
aes(
Experience,
Salary
)
) +
geom_point(
color = "blue",
size = 3
) +
geom_line(
color = "gray"
)đ Adding Regression Lines
The geom_smooth() layer adds trend or regression lines.
Regression Line
ggplot(
employees,
aes(
Experience,
Salary
)
) +
geom_point() +
geom_smooth(
method = "lm",
se = TRUE,
color = "red"
)đĻ Advanced Bar Charts
Grouped Bar Chart
sales <- data.frame(
Department = c(
"IT",
"IT",
"HR",
"HR"
),
Quarter = c(
"Q1",
"Q2",
"Q1",
"Q2"
),
Revenue = c(
120,
150,
100,
130
)
)
ggplot(
sales,
aes(
Department,
Revenue,
fill = Quarter
)
) +
geom_col(
position = "dodge"
)đ Stacked and Filled Bar Charts
Stacked Bars
ggplot(
sales,
aes(
Department,
Revenue,
fill = Quarter
)
) +
geom_col()Filled Bars
ggplot(
sales,
aes(
Department,
Revenue,
fill = Quarter
)
) +
geom_col(
position = "fill"
)đ¯ Faceting
Faceting creates multiple plots based on categorical variables.
Using facet_wrap()
ggplot(
employees,
aes(
Experience,
Salary
)
) +
geom_point() +
facet_wrap(
~ Department
)Using facet_grid()
ggplot(
sales,
aes(
Quarter,
Revenue
)
) +
geom_col() +
facet_grid(
Department ~ .
)đ¨ Customizing Scales
Scales control colors, labels, limits, and axis formatting.
Custom Colors
ggplot(
employees,
aes(
Experience,
Salary,
color = Department
)
) +
geom_point(
size = 4
) +
scale_color_manual(
values = c(
"IT" = "blue",
"HR" = "green",
"Finance" = "red"
)
)đ Coordinate Systems
Coordinate systems change the way data is displayed.
Horizontal Bar Chart
ggplot(
sales,
aes(
Department,
Revenue
)
) +
geom_col() +
coord_flip()Polar Chart
ggplot(
sales,
aes(
"",
Revenue,
fill = Department
)
) +
geom_col(
width = 1
) +
coord_polar(
theta = "y"
)đ Adding Text Labels
Using geom_text()
ggplot(
employees,
aes(
Experience,
Salary,
label = Name
)
) +
geom_point(
size = 3
) +
geom_text(
vjust = -0.8
)đ Annotating Plots
The annotate() function adds explanatory text, arrows, or shapes.
Annotations
ggplot(
employees,
aes(
Experience,
Salary
)
) +
geom_point() +
annotate(
"text",
x = 6,
y = 80000,
label = "Highest Salary",
color = "red"
)đ Advanced Themes
Themes control fonts, backgrounds, grid lines, and other visual elements.
Customized Theme
ggplot(
employees,
aes(
Experience,
Salary
)
) +
geom_point() +
theme_minimal() +
theme(
plot.title = element_text(
size = 18,
face = "bold"
),
axis.title = element_text(
size = 14
),
panel.grid.major = element_line(
color = "gray80"
)
) +
labs(
title = "Employee Salary Analysis"
)đ Statistical Transformations
Statistical layers summarize data automatically.
Density Plot
ggplot(
employees,
aes(
Salary
)
) +
geom_density(
fill = "skyblue",
alpha = 0.5
)Violin Plot
ggplot(
employees,
aes(
Department,
Salary,
fill = Department
)
) +
geom_violin()đ Combining Geometries
Line and Points
salesTrend <- data.frame(
Month = 1:6,
Sales = c(
120,
150,
170,
165,
190,
210
)
)
ggplot(
salesTrend,
aes(
Month,
Sales
)
) +
geom_line(
color = "blue",
linewidth = 1.2
) +
geom_point(
color = "red",
size = 3
)đž Saving High-Quality Graphics
Saving a Plot
plot <- ggplot(
employees,
aes(
Experience,
Salary
)
) +
geom_point()
ggsave(
filename = "employee_plot.png",
plot = plot,
width = 8,
height = 6,
dpi = 300
)đ Real-World Example
A company wants to analyze employee salaries across departments while identifying overall trends.
Employee Salary Dashboard
ggplot(
employees,
aes(
Experience,
Salary,
color = Department
)
) +
geom_point(
size = 4
) +
geom_smooth(
method = "lm",
se = FALSE,
color = "black"
) +
facet_wrap(
~ Department
) +
labs(
title = "Salary Analysis by Department",
x = "Years of Experience",
y = "Salary"
) +
theme_minimal()đ Advanced ggplot2 Workflow
đ Common Advanced Functions
| Function | Purpose |
|---|---|
| geom_smooth() | Adds trend or regression lines. |
| facet_wrap() | Creates multiple panels. |
| facet_grid() | Creates grid layouts. |
| scale_color_manual() | Customizes colors. |
| coord_flip() | Flips coordinate axes. |
| coord_polar() | Creates circular charts. |
| annotate() | Adds annotations. |
| ggsave() | Exports plots. |
â ī¸ Common Mistakes
| Mistake | Explanation | Solution |
|---|---|---|
| Mapping fixed values inside aes() | Creates unnecessary legends. | Place constant values outside aes(). |
| Adding too many layers | Plots become cluttered and difficult to interpret. | Include only layers that improve understanding. |
| Using inappropriate scales | Can misrepresent the data. | Choose scales suitable for the variables. |
| Ignoring themes and labels | Plots appear unprofessional. | Add descriptive titles, labels, and a suitable theme. |
đĄ Best Practices
- Build plots incrementally by adding one layer at a time.
- Use faceting to compare categories effectively.
- Apply consistent colors and themes throughout a project.
- Use annotations to highlight key insights.
- Export graphics with high resolution for reports and publications.
Best Practice
đ Summary
Advanced ggplot2 extends basic visualization techniques by introducing layered graphics, statistical transformations, faceting, advanced themes, coordinate systems, annotations, custom scales, and high-quality plot exports. By mastering these features, you can create professional, publication-ready visualizations that effectively communicate complex data and analytical insights.