Advanced ggplot2 in R

📘 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

One of the greatest strengths of ggplot2 is its layered grammar, allowing you to build complex visualizations by adding components one layer at a time.

đŸŽ¯ 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

Prepare Data
Create ggplot Object
Add Geometric Layers
Apply Statistical Layers
Customize Scales and Themes
Annotate Plot
Export Visualization

📋 Common Advanced Functions

FunctionPurpose
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

MistakeExplanationSolution
Mapping fixed values inside aes()Creates unnecessary legends.Place constant values outside aes().
Adding too many layersPlots become cluttered and difficult to interpret.Include only layers that improve understanding.
Using inappropriate scalesCan misrepresent the data.Choose scales suitable for the variables.
Ignoring themes and labelsPlots 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

Advanced ggplot2 techniques allow you to transform raw data into clear, compelling visual stories. Combining multiple layers, thoughtful aesthetics, and effective annotations produces graphics that are both informative and visually appealing.

📝 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.

>>"Advanced ggplot2 empowers you to turn data into compelling visual narratives through layered design, thoughtful customization, and meaningful presentation."