ggplot2 Fundamentals in R

📘 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

Unlike Base Graphics, ggplot2 creates plots by adding layers using the + operator, making the code modular and easy to extend.

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

Data
Aesthetic Mappings
Geometric Objects
Scales
Labels
Themes
Final Plot

📚 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

ThemeDescription
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

Prepare Data
Create ggplot Object
Add Geometric Layers
Customize Aesthetics
Add Labels and Themes
Display or Save Plot

📋 Common Geometric Layers

GeometryPurpose
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

MistakeExplanationSolution
Forgetting to load ggplot2The ggplot() function will not be available.Run library(ggplot2) before creating plots.
Using incorrect aesthetic mappingsVariables may not display correctly.Place variable mappings inside aes().
Using geom_line() without groupingLines may not connect as expected for categorical x-values.Specify group = 1 or an appropriate grouping variable.
Confusing mapped aesthetics with fixed valuesColors 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

ggplot2 follows a layered approach that makes complex visualizations easier to build and maintain. By combining data, aesthetics, geometric layers, labels, and themes, you can create professional-quality graphics for analysis, reports, and presentations.

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

>>"ggplot2 transforms data into elegant visual stories, making complex information clear, insightful, and easy to understand."