Data Visualization with R
Introductory Data Visualization with ggplot2
Why use ggplot2?
ggplot2 is an R package for creating data visualizations based on the Grammar of Graphics. It is widely used in data science because it can produce polished, publication-quality plots with relatively little code, while also allowing detailed control over how a graphic looks.
A key practical advantage is that visualizations can be built incrementally. Once a basic plot has been written, it is often efficient to copy it and modify a few parts to investigate a new question. This makes it straightforward to explore the same data from several perspectives.
Visualizations are especially useful when an audience is not familiar with statistical terminology. People can often recognize patterns, comparisons, and proportions in a well-designed graphic more easily than in a list of summary statistics. Plots can therefore help analysts explain findings, as well as explore data themselves.
The Grammar of Graphics
A ggplot2 visualization is assembled from several interacting components. Together, these components describe what data is shown, how it is represented, and how the finished plot is presented.
Data
The data is the raw material for the plot. It is generally supplied as a data frame, with rows representing observations and columns representing variables.
Aesthetic mappings
An aesthetic mapping connects variables in the data to visual properties of the plot. For example, a variable can be mapped to the horizontal axis, vertical axis, color, or fill.
If passenger age is mapped to the vertical axis, ggplot2 uses the values in the age column to determine the plotted positions. Mapping a categorical variable to fill can assign different colors to categories, making group comparisons easier to see.
Layers
Layers determine what graphical marks appear in the visualization, such as bars, points, lines, or density curves. In ggplot2, layer functions commonly begin with geom_.
The choice of layer depends on the data and the question. For example, a bar chart can display counts of categories, while a histogram displays the distribution of a numeric variable.
Scales
Scales control how data values are translated into visual values, such as positions, colors, and sizes. They help map a variable’s range onto the available plotting area. Many plots use suitable default scales, but scales can be customized when a particular presentation is needed.
Coordinates
Coordinates determine the plot’s spatial system. Most common visualizations use a two-dimensional horizontal and vertical coordinate grid. ggplot2 supports other coordinate systems, but the standard grid is suitable for many everyday plots.
Faceting
Faceting divides data into subsets and displays those subsets in separate panels. This makes it possible to compare patterns across categories without combining every group into one crowded plot.
Themes
Themes control the non-data appearance of a plot, including background, text, font sizes, and other display details. A theme can give a graphic a cleaner or more consistent appearance without changing the data being shown.
In practice, many plots need only three essentials: data, aesthetic mappings, and a layer. Scales, coordinates, facets, and themes provide additional control when the defaults are not sufficient.
A basic ggplot2 plot follows this general pattern:
ggplot(data, aes(x = variable)) +
geom_bar()This tells ggplot2 which data to use, maps a variable to the horizontal axis, and adds a bar-chart layer. Additional layers and settings can be added to build on the plot.
Example Data: Titanic Passengers
The Titanic passenger data provides a familiar example for exploring visualizations. It contains 891 observations and 12 columns. Its subject is widely understood, and the data resembles business data in useful ways: it includes different kinds of variables, missing values, and fields whose meanings may be less straightforward than their names suggest.
Variables in the data
Survived: A binary indicator. A value of zero means the passenger died; a value of one means the passenger survived.
Pclass: Ticket class: first, second, or third. It represents categories of accommodation, not a numeric quantity suitable for arithmetic.
Sex: The passenger’s recorded sex, represented as male or female in this data.
Age: Passenger age, a numeric, continuous variable.
SibSp: The number of siblings or a spouse traveling with the passenger. The field combines related but distinct relationships.
Parch: The number of parents or children traveling with the passenger. This field also combines different relationships.
Ticket: The passenger’s ticket identifier.
Fare: The amount paid for the ticket, recorded in pounds sterling.
Cabin: The cabin identifier, when one was recorded.
Embarked: The port where the passenger boarded: Cherbourg, Queenstown, or Southampton.
PassengerId: A unique passenger identifier.
Name: The passenger’s name.
The SibSp and Parch fields illustrate a common issue in real-world data: a column can be overloaded, holding a value that combines multiple concepts. For instance, SibSp counts siblings and spouses in one field. Such fields should be interpreted carefully, because the same recorded value may not have exactly the same meaning in every case.
Passenger IDs and names are not useful as ordinary numeric or categorical predictors in their raw form. Every passenger has a unique ID and name, so simply plotting them would not reveal meaningful group patterns. Text analysis could potentially extract useful information from names, but that is a separate analytical task.
Preparing Variables for Visualization
Categorical variables and factors
CSV files may cause R to interpret category codes as numeric values. The analyst must consider what the values mean, rather than relying only on their storage format.
For example, Survived is stored as zero or one, but it represents two categories: did not survive and survived. Pclass is stored as one, two, or three, but those numbers identify ticket classes. They do not mean that third class is three times first class, or that first class is one-third of third class.
These fields should be treated as factors, or categorical variables. Sex and Embarked are categorical as well. Correctly identifying factors helps ggplot2 handle categories appropriately, including when assigning colors or displaying category labels.
A useful diagnostic question is whether arithmetic on the values would make sense. Multiplication or division of survival codes or ticket-class labels is not meaningful, so those variables should not be treated as ordinary numeric measurements.
Missing values
Some passenger ages are missing: 177 age values are absent in this dataset. ggplot2 can omit missing values when creating a plot and generally reports how many values were removed. This allows a plot to be created from available observations, but it does not resolve the underlying data-quality issue.
An analyst may need to decide later whether to exclude rows, investigate why the values are missing, or estimate the missing ages. That decision depends on the analytical purpose. A plot that omits missing values should not be interpreted as if it necessarily represents every passenger.
Choosing Visualizations for the Question
A plot should be selected according to the kind of variable being examined and the question being asked.
Bar charts are useful for categorical variables. They show counts by category.
Histograms show the distribution of a numeric variable by grouping its values into intervals, called bins.
Box-and-whisker plots summarize and compare the distributions of a numeric variable across groups.
Density plots show a smoothed representation of a numeric distribution.
Faceted plots repeat a visualization across subsets, making patterns across groups easier to compare.
The same dataset can support several complementary plots. Each one may reveal a different aspect of the pattern, so relying on a single visualization can provide an incomplete picture.
Overall Survival
A useful starting question is how many passengers survived and how many did not. Because Survived is categorical, a bar chart is a natural choice. With a bar-chart layer and no separate count variable, ggplot2 counts the observations in each category.
ggplot(titanic, aes(x = Survived)) +
geom_bar()The resulting chart compares the number of passengers who died with the number who survived. It shows that more passengers died than survived. The approximate counts are about 550 deaths and 340 survivors.
To calculate exact relative proportions separately, the table of counts can be converted to proportions with R’s prop.table() function. In this dataset, approximately 62% died and 38% survived. The plot helps communicate the imbalance visually, while a proportion calculation provides a more precise value than estimating from bar heights.
Improving plot labels and appearance
A chart intended for others should have informative labels and a clear title. The axis label should describe what is being counted, and a title should communicate the subject of the plot. Themes can also change the display; for example, a white background may be preferred over ggplot2’s default gray background.
The labs() function can set axis labels and the plot title. This kind of adjustment improves readability without changing the underlying counts.
Comparing Survival by Sex
A next question is whether survival differed by sex. A bar chart can show the passenger counts by sex, with each bar divided by survival outcome. Mapping Survived to fill gives the survival categories different colors.
ggplot(titanic, aes(x = Sex, fill = Survived)) +
geom_bar()This plot shows both group size and the count of survivors and deaths within each sex. In the data, the largest portion of the male passenger count represents passengers who died, while most female passengers survived. There were also substantially more male passengers than female passengers—roughly twice as many.
A stacked bar chart displays counts, not automatically normalized percentages. Comparing the size of colored sections within bars can suggest relative survival patterns, but exact rates should be calculated separately or shown with an appropriate proportion-based visualization.
This pattern is consistent with the idea that women were more likely to survive, but the chart alone does not establish why the difference occurred. It shows an association in this dataset, not proof of a cause.
Comparing Survival by Ticket Class
Ticket class may also be associated with survival. Mapping Pclass to the horizontal axis and Survived to fill produces a bar chart showing passenger counts and outcomes for each class.
The chart indicates that survival was highest in first class and lowest in third class. More than half of first-class passengers survived, while survival in third class was much lower—approximately one in four. Second-class survival lies between these patterns, at roughly half.
The passenger counts are not ordered in the way one might expect from ticket price alone: the second-class group is smaller than both the first- and third-class groups. This illustrates why plots can be useful for checking assumptions about data rather than relying on intuition.
Possible explanations for differences by class might include passengers’ location on the ship or their access to lifeboats. The visualization itself cannot determine which explanation is correct; it identifies a pattern that could motivate further investigation.
Combining Sex and Class with Faceting
A plot can examine sex and ticket class together by using faceting. For example, the data can be divided into separate panels by class, while each panel compares the sexes and survival outcomes.
ggplot(titanic, aes(x = Sex, fill = Survived)) +
geom_bar() +
facet_wrap(~ Pclass)Each panel represents one ticket class. Within each panel, the bars compare female and male passengers, and the colors distinguish survival outcomes.
The combined view reveals that survival patterns differ across groups:
Female passengers in first and second class overwhelmingly survived.
Female survival in third class was lower than in the upper classes, though many still survived.
Male survival was generally much lower than female survival across the classes.
Among male passengers, first class appears to have the best survival, while third class has the worst.
Third class contained many more male than female passengers.
Faceting is useful because it preserves comparisons within each subset while displaying the subsets side by side. It can reveal interactions between variables that might be hidden in a single overall chart.
Exploring Age Distributions
Age is numeric and continuous, so a bar chart of individual ages is generally not the most useful summary. A histogram groups ages into intervals and counts how many observations fall in each interval.
ggplot(titanic, aes(x = Age)) +
geom_histogram(binwidth = 5)The binwidth determines how wide each age interval is. A width of five groups ages into five-year bins. Changing the bin width changes the plot’s appearance and can alter which patterns are easy to see. A very wide bin may conceal detail; a very narrow bin may produce a noisy or overly fragmented display. Different bin widths should be tried to find one that communicates the distribution appropriately.
The age histogram shows that many passengers were between about 20 and 40 years old. The distribution also has a long tail toward older ages, with relatively few elderly passengers. There were some children and some passengers as old as about 80.
The plot omits the 177 passengers whose ages are missing and reports that omission. The resulting distribution therefore describes passengers with recorded ages, not necessarily the full passenger population.
Adding survival information to the age histogram
Survival can be mapped to fill so that each age bin shows the counts of passengers who survived and those who died.
ggplot(titanic, aes(x = Age, fill = Survived)) +
geom_histogram(binwidth = 5)This plot retains the age distribution while adding information about survival within each age interval. It suggests that younger children often had comparatively high survival, while many older passengers died. Survival among adults varied across age groups.
As with the sex and class bar chart, the stacked histogram primarily displays counts. The number of passengers in each age interval differs, so colored sections should be interpreted in light of the size of each bin rather than treated automatically as exact survival rates.
Box-and-Whisker Plots
A box-and-whisker plot provides a compact summary of a numeric distribution and is useful for comparing that distribution across categories. In this example, age is plotted vertically and survival status horizontally.
ggplot(titanic, aes(x = Survived, y = Age)) +
geom_boxplot()The plot suggests that passengers who survived tended to be somewhat younger than those who died. The difference is visible but not large in the overall age summaries.
A boxplot is valuable because it summarizes a distribution rather than showing every observation. However, it can conceal details within the distribution. In this example, it does not communicate the especially high survival among some child age groups as clearly as the histogram with survival coloring. Using both plots provides a fuller view: the boxplot summarizes and compares age distributions, while the histogram shows how outcomes vary across age intervals.
Exploring Age, Sex, and Class Together
Age can be examined jointly with sex, class, and survival using a faceted plot. A density plot provides a smoothed view of age distributions, while faceting creates panels for combinations of sex and ticket class.
ggplot(titanic, aes(x = Age, fill = Survived)) +
geom_density(alpha = 0.5) +
facet_wrap(~ Sex + Pclass)A density plot is related to a histogram: both represent the distribution of a numeric variable. A density plot replaces discrete bars with a smoothed curve. The alpha setting controls transparency. Partially transparent fills help reveal overlapping areas that might be hidden if the plotted regions were opaque.
In the faceted density plot, each panel represents a sex-and-class combination. The plot suggests that age, sex, and class together are more informative than age alone. For example, young passengers in some class-and-sex groups show notably high survival. The patterns differ across panels, so a single overall age distribution would not tell the whole story.
A histogram can be faceted in the same way. Histograms retain explicit age bins, which may make counts within specific intervals easier to inspect. In the Titanic example, the faceted histogram makes it easier to see how survival counts vary by age group across the sex-and-class panels. The density plot and histogram are complementary: smoothing can make broad shapes easier to recognize, while bins can make local counts and age ranges more explicit.
These plots also reinforce that an apparent overall pattern can conceal substantial variation among subgroups. For instance, survival among younger passengers does not appear identical across all classes and sexes. The combined visualization suggests that outcomes are associated with the interaction of age, sex, and class, rather than with age considered in isolation.
Practical Principles for Using ggplot2
Start with the question and the data type. Use bar charts for categories and histograms, density plots, or boxplots for numeric distributions.
Map variables deliberately. An axis mapping determines position; a
fillmapping can distinguish groups by color.Treat categories as categories. Numeric-looking codes such as survival indicators and ticket classes may not represent quantities suitable for arithmetic.
Use faceting to compare subsets. Separate panels can make patterns across groups clearer without overcrowding one plot.
Adjust plot settings when needed. Labels, themes, bin widths, and transparency can improve the plot’s readability.
Use several views of the data. Different plot types reveal different aspects of a distribution, and agreement across views can strengthen understanding.
Distinguish counts from rates. A stacked chart often shows counts; exact proportions may require separate calculation or a proportion-oriented plot.
Treat visual patterns as evidence for questions, not automatic explanations. A plot can reveal associations and suggest hypotheses, but it does not by itself establish causation.
ggplot2 makes it practical to move from a basic plot to a more informative one by changing mappings, layers, and presentation settings while keeping the same underlying data.

Ask anything
We've read this whole study set, so questions about it get the best answers.