Data Visualization in R using GGPlot2
This lecture provides a comprehensive introduction to data visualization in R, with a strong
emphasis on the `ggplot2` library, one of R's most powerful and widely used tools for creating
sophisticated graphics.
### I. Introduction to Data Visualization
Data visualization is crucial for understanding data patterns and communicating insights
effectively. Our innate ability to see patterns makes visual displays an efficient way to interpret
data.
Exploratory Data Visualization: This type of visualization helps us understand the data itself. The
key is to keep all potentially relevant details together, allowing for the discovery of underlying
structures and relationships. The main objective is to help you see what's in your data.
Explanatory Data Visualization: This type focuses on sharing our understanding with others. It
involves making editorial decisions about what features to highlight for emphasis and what
might be distracting or confusing to eliminate.
R provides various tools and packages for creating both types of data visualizations.
### II. Core R Functions for Plotting
R's base graphics system offers several fundamental functions for creating plots:
`plot()`: A generic function used for various types of plotting, often generating scatter plots or
line plots depending on the data.
`barplot()`: Used to create bar charts, which represent data using rectangular bars.
`hist()`: Used to create histograms, which visualize the frequency distribution of a single
variable.
`boxplot()`: Represents data in the form of quartiles, useful for identifying central tendency and
outliers.
`ggplot()`: This is a package that enables the creation of sophisticated visualizations with
minimal code, based on the "grammar of graphics."
`plotly()`: Creates interactive web-based graphs using an open-source JavaScript graphing
library.
### III. Types of Graphics Systems in R
R offers different graphic systems, each with its characteristics:
Base Graphics: These are the easiest to learn and are often used for quick and simple plots.
They are built directly into R.
Grid Graphics: A powerful set of modules that serve as a foundation for building other plotting
tools. While they have a steeper learning curve, they offer much more power and flexibility than
base graphics.
Lattice Graphics: A general-purpose system built on grid graphics, designed for visualizing
multivariate data.
GGPlot2: This highly popular package implements the "grammar of graphics" and is also based
on grid graphics. It provides a structured and flexible approach to building complex plots layer
by layer.
### IV. Introduction to GGPlot2
`ggplot2` is a fundamental package for creating graphs in R, part of the `tidyverse` ecosystem.
Its strength lies in its "grammar of graphics," a method of thinking about and decomposing
complex graphs into logical subunits.
Key Components of GGPlot2: `ggplot2` allows users to build graphs by specifying components
such as data, aesthetics (mappings of variables to visual properties like x-axis, y-axis, color,
size), and geometric objects (`geoms`).
Flexibility and Defaults: Users can modify each component in a flexible way. If specific details for
components are not provided, `ggplot2` will use sensible defaults, making it both powerful and
user-friendly.
### V. Geometric Objects (`geoms`) in GGPlot2
Geometric objects (or `geoms`) form the basis of different types of graphs in `ggplot2`. They
dictate the visual representation of your data.
`geom_bar()`: For bar charts.
`geom_line()`: For line graphs.
`geom_point()`: For scatter plots.
`geom_boxplot()`: For box plots.
`geom_violin()`: For richer displays of data distribution.
`geom_jitter()`: Useful for small datasets to avoid overplotting.
### VI. Types of Charts and Their Creation
The lecture demonstrates how to create various types of charts using both base R functions and
`ggplot2`.
#### A. Bar Charts
Definition: Bar charts show comparisons across discrete categories. The x-axis typically shows
categories, and the y-axis represents a measured value. The height of the bars is proportional
to these measured values.
Creating Bar Charts with GGPlot2:
Simple Bar Charts: Use `ggplot()` to define the data and aesthetics (e.g., mapping a categorical
variable to the x-axis), then add `geom_bar()`. Colors can be added to enhance meaning.
Stacked Bar Charts: Achieved by mapping a variable to the `fill` aesthetic within `geom_bar()`.
This stacks segments of bars based on the `fill` variable's categories.
Dodged Bar Charts: Instead of stacking, bars are placed next to each other by setting `position
= "dodge"` within `geom_bar()`.
#### B. Line Graphs
Definition: Displays information as a series of data points connected by straight line segments,
often used to show trends over time or ordered categories.
Creating Line Graphs with GGPlot2: Use `geom_line()` to connect data points.
#### C. Scatter Plots
Definition: A two-dimensional data visualization that uses points to graph the values of two
different variables, one on the x-axis and one on the y-axis. They are primarily used to assess
the relationship or lack of relationship between two variables.
Creating Scatter Plots:
Base R: The `plot()` function can create basic scatter plots.
GGPlot2: Use `ggplot()` with aesthetics for x and y variables, then add `geom_point()`. Scatter
plots can also be colored or sized based on factors (categorical variables) to reveal group-wise
relationships.
#### D. Histograms
Definition: Used to visualize the distribution of a single continuous variable. The x-axis
represents bins (intervals of values), and the y-axis represents the frequency or count of data
points falling into each bin. They help in understanding central tendency and the spread of data.
Creating Histograms:
Base R: The `hist()` function is used. You can specify x-axis labels, colors, borders, and even
set x-axis and y-axis limits (`xlim`, `ylim`).
Non-Uniform Width Histograms: `hist()` can be configured with `breaks` to create bins of varying
widths, depending on the data characteristics.
#### E. Box Plots
Definition: Represents data in the form of quartiles, showing the median, interquartile range
(IQR), and potential outliers. They are excellent for visualizing data distribution and identifying
outliers.
Creating Box Plots:
Base R: The `boxplot()` function can create multiple box plots based on different columns or
groups within a dataset. Individual dots beyond the "whiskers" indicate outliers.
GGPlot2: Use `ggplot()` with appropriate aesthetics (e.g., a categorical variable on the x-axis
and a continuous variable on the y-axis), and then add `geom_boxplot()`. `ggplot2` allows for
flipping coordinates or filling colors based on factors for more detailed visualization.
#### F. Pie Charts
Definition: Circular statistical graphics divided into slices to illustrate numerical proportion. Each
slice represents a category's proportion of the whole.
Creating Pie Charts:
Base R: The `pie()` function is used. You can provide numerical values and labels for each slice.
It's also possible to calculate percentages and display them directly on the chart.
3D Pie Charts: Requires the `plotrix` package and its `pie3D()` function to create a
three-dimensional representation. Options like `explode` control how the slices are visually
separated.
### VII. Advanced GGPlot2 Concepts and Interactive Plots
Factors: When working with categorical variables in `ggplot2` (e.g., for coloring or grouping), it's
often beneficial to convert them to factors and assign meaningful levels and labels.
Plotly Integration: The `plotly` package allows for creating interactive, web-based graphs directly
from `ggplot2` objects or by building plots explicitly with `plot_ly()`. This adds interactivity such
as zooming, panning, and hover-over information.
This lecture highlights that R, especially with `ggplot2`, offers immense flexibility and power for
data visualization, catering to both exploratory data analysis (to understand your data) and
explanatory data analysis (to share your findings). The key is to select the appropriate plot type
and utilize the extensive customization options available.