Data Visualization with R
Introductory Data Visualization with R and ggplot2
Why visualization matters
Data visualization turns information in a dataset into a form people can inspect quickly. A chart can make a pattern—such as one group having higher survival than another—easier to recognize than a table of numbers or a set of summary statistics. This is especially useful when findings need to be explained to an audience that is not comfortable with technical analysis.
A visualization is not just decoration. It is a way to ask a question of data and communicate the answer. The choice of variables and chart type shapes what can be seen, so the analyst needs to understand both the data and the question being explored.
For example, a question about how many people survived calls for a different visual approach from a question about the distribution of passenger ages. The first concerns categories and counts; the second concerns numeric values and their spread.
Think About It: What kind of pattern would be easier to notice in a chart than in a list of passenger records?
The example data: Titanic passengers
The Titanic passenger data provides a familiar setting for learning visualization. It contains 891 observations—one for each passenger represented in the dataset—and 12 columns describing those passengers. The dataset is also a useful example of business data: it contains a mix of numeric and categorical fields, missing values, and columns whose meanings require care.
Important fields include:
- Survived: A binary indicator: zero means the passenger died, and one means the passenger survived.
- Pclass: The passenger’s ticket class: first, second, or third class.
- Sex: The passenger’s recorded gender category.
- Age: Passenger age, represented numerically.
- SibSp: The number of siblings or a spouse traveling with the passenger.
- Parch: The number of parents or children traveling with the passenger.
- Ticket: The ticket’s identifying number.
- Fare: The amount paid, in pounds sterling.
- Cabin: A cabin identifier, present for only some passengers.
- Embarked: The port where the passenger boarded, represented by codes for Cherbourg, Queenstown, and Southampton.
The meanings of SibSp and Parch illustrate an important data problem: a field can combine several related meanings. SibSp, for instance, counts siblings and spouses in the passenger’s traveling party. Such fields can be convenient to store, but they may require careful interpretation before analysis.
The dataset also includes PassengerId and Name. A passenger ID is a unique identifier, and each name in this data is unique. Neither field, in its raw form, provides an obvious group pattern for a basic chart. Names might become analytically useful if text analysis were applied, but that is a different task.
Categories and numeric values
A column’s storage format does not always capture its analytical meaning. When a CSV file is read into R, Survived and Pclass may be interpreted as numbers because they contain digits. Yet they represent categories: survival versus non-survival, and first-, second-, or third-class travel.
The distinction matters because the numbers in these fields are labels, not measurements. A third-class ticket is not three times a first-class ticket, and survival values are not quantities to multiply or divide. Such columns are better treated as factors, R’s representation for categorical variables. Sex and Embarked are categorical as well.
By contrast, Age is a numeric variable: differences between values have a meaningful interpretation. Recognizing whether a field is categorical or numeric helps determine which visualizations make sense. Bar charts are well suited to categories, while histograms and density plots are commonly used to examine numeric distributions.
Think About It: Why would it be misleading to treat ticket class as a numeric measurement rather than a category?
What ggplot2 does
ggplot2 is a widely used R package for creating data visualizations. Its name refers to the grammar of graphics: a way of constructing a chart by combining parts that each have a clear role. Rather than choosing a chart from a menu, an analyst describes the data to use, how its variables should appear, and what kind of marks should be drawn.
This approach makes ggplot2 useful both for quick charts and for detailed customization. Its default settings often produce a readable result with little code. When a chart needs a different title, background, scale, or arrangement, additional parts can be added.
The six parts of the grammar
A visualization in ggplot2 can involve six main components:
- Data supplies the observations and variables to visualize.
- Layers are the visible marks in the chart, such as bars, points, lines, or curves.
- Scales translate data values into visual values, such as positions, colors, or sizes. They help fit the data into the available plotting space and determine how visual encodings correspond to data values.
- Coordinates define the chart’s spatial system. Most introductory charts use a two-dimensional grid with horizontal and vertical axes.
- Faceting divides data into subsets and displays those subsets in separate panels, making comparisons easier.
- Themes control the presentation of chart elements such as fonts, backgrounds, and other display details.
Not every chart requires the analyst to adjust every component. ggplot2 supplies defaults for many decisions. The components are useful to understand because they explain how a chart is built and where to make changes when the default result is not suitable.
The essential starting point
A simple ggplot2 chart usually needs three things:
- The data to plot.
- An aesthetic mapping that connects variables to visual properties, such as the horizontal axis, vertical axis, or fill color.
- A geometry, or
geom, that specifies the marks to draw.
For example:
ggplot(titanic, aes(x = Survived)) +
geom_bar()
Here, ggplot() starts a plot using the titanic data frame. The aes() function maps the Survived variable to the horizontal axis. geom_bar() adds bars and, by default, counts the observations in each category.
The aesthetic mapping answers a question such as, “Which variable should determine the horizontal position?” A mapping can also assign a variable to y, fill, or other visual properties. The geometry answers, “What kind of mark should represent the data?” Many geometry functions begin with geom_, including geom_bar(), geom_histogram(), and geom_boxplot().
Think About It: In the example, which part identifies the variable, and which part chooses the chart marks?
Preparing data for a chart
Before plotting, an analyst should check whether the variables have been read with appropriate types. A basic factor conversion in R might look like this:
titanic$Survived <- factor(titanic$Survived)
titanic$Pclass <- factor(titanic$Pclass)
titanic$Sex <- factor(titanic$Sex)
titanic$Embarked <- factor(titanic$Embarked)
Treating these fields as factors signals to ggplot2 that they are categories. This can affect how values are displayed and makes categorical variables available for mappings such as fill.
The age field contains missing values. In the example analysis, 177 ages are missing. When a plot uses Age, ggplot2 omits rows with missing ages from that plot and reports how many values were removed. The resulting chart can still be useful, but the warning matters: the analyst should remember that the visualization covers only passengers with recorded ages. Depending on the task, missing values might later need to be investigated, removed deliberately, or estimated. For the introductory charts, the key point is simply to notice their effect.
Exploring categorical variables
Overall survival counts
A first useful question is how many passengers survived and how many did not. Because Survived is categorical, a bar chart is a natural choice:
ggplot(titanic, aes(x = Survived)) +
geom_bar()
The bars show counts for the two categories. The chart makes the broad pattern apparent: more passengers died than survived. A table can give exact counts, while the chart makes their relative sizes easy to compare.
The overall survival proportions can also be calculated separately. In this dataset, roughly 62% of passengers died and 38% survived. The chart gives an intuitive visual check of that relationship, though the percentages are not printed on the bars in this basic version.
Improving labels and appearance
A chart becomes easier to interpret when its labels explain what is being counted. The labs() function can set axis labels and a title. A theme can adjust visual presentation:
ggplot(titanic, aes(x = Survived)) +
geom_bar() +
labs(
x = "Survival status",
y = "Passenger count",
title = "Titanic survival rates"
) +
theme_bw()
The example uses a clean white-background theme rather than ggplot2’s default gray background. A clear title and axis labels help a reader understand the chart without needing to infer what “count” or a numeric category means.
A practical feature of ggplot2 is that a chart can be copied and adapted. After creating one visualization, an analyst can often reuse most of its code and change the mapping, geometry, labels, or other settings. This makes it efficient to explore related questions consistently.
Survival by gender
The next question is whether survival differed by gender. The fill aesthetic can color the bars according to another categorical variable:
ggplot(titanic, aes(x = Sex, fill = Survived)) +
geom_bar() +
labs(
x = "Sex",
y = "Passenger count",
title = "Titanic survival by sex"
) +
theme_bw()
Each bar represents a gender category, and its segments distinguish survival outcomes. The chart shows a striking pattern: many more male passengers died than survived, while most female passengers survived. It also shows that there were more male passengers than female passengers.
This kind of chart supports a business-style explanation because both the group sizes and their survival outcomes are visible. However, a stacked count chart should be read with care: its total bar heights reflect the number of passengers in each group, while the segment sizes show how those counts are divided between outcomes. It helps reveal a pattern, but exact survival rates require comparing each outcome with its group’s total.
Survival by ticket class
Ticket class may also be related to survival. The same chart structure can be reused by changing the horizontal-axis variable:
ggplot(titanic, aes(x = Pclass, fill = Survived)) +
geom_bar() +
labs(
x = "Ticket class",
y = "Passenger count",
title = "Titanic survival by ticket class"
) +
theme_bw()
The chart suggests declining survival as class moves from first to third. More than half of first-class passengers survived, while the survival share in third class was much lower—approximately one in four. The counts also reveal that the groups were not equally large: there were fewer second-class passengers than either first- or third-class passengers.
A visualization helps examine a proposed explanation, such as whether passengers in higher classes may have been closer to lifeboats. The chart displays an association between class and survival; by itself, it does not prove why that association occurred.
Think About It: What can a stacked bar chart show about group size that a chart showing only survival percentages might hide?
Faceting: comparing subsets in separate panels
When more than one categorical variable may matter, faceting can divide a chart into panels. This makes it possible to compare the same relationship across subsets of the data.
ggplot(titanic, aes(x = Sex, fill = Survived)) +
geom_bar() +
facet_wrap(~ Pclass) +
labs(
x = "Sex",
y = "Passenger count",
title = "Titanic survival by sex and ticket class"
) +
theme_bw()
The tilde in facet_wrap(~ Pclass) can be read as “make a panel for each value of Pclass.” The result contains separate panels for first, second, and third class. Each panel compares female and male passengers while retaining the survival color coding.
This view reinforces several patterns: women in first and second class overwhelmingly survived, and women in third class also had a substantial survival share. Male passengers had lower survival overall. The chart also makes it possible to compare the relative numbers of women and men within each ticket class; third class contained many more men than women.
Faceting is a form of visual drill-down. It resembles examining a pivot chart after dividing a dataset by categories: instead of combining every subset into one crowded display, the visualization gives each subset a panel.
Exploring numeric data
Categorical charts answer questions about counts across groups. For a numeric variable such as age, the analyst often wants to understand its distribution: where values cluster, how widely they vary, and whether the data has a long tail.
Histograms and bin width
A histogram groups numeric values into intervals called bins and displays the count in each interval. The geom_histogram() geometry can be used to examine passenger ages:
ggplot(titanic, aes(x = Age)) +
geom_histogram(binwidth = 5) +
labs(
x = "Age",
y = "Passenger count",
title = "Passenger age distribution"
) +
theme_bw()
Here, binwidth = 5 groups ages into intervals five years wide. Bin width matters because it changes the shape of the histogram. Wide bins smooth over detail; narrow bins reveal more local variation but can make a chart look jagged. The default width may not be the most useful choice, so it is often worth comparing several reasonable widths.
The age histogram shows a concentration of passengers between about 20 and 40 years old, a smaller number of children, and a long tail toward older ages. It also shows that there were passengers as old as about 80. Since ages are missing for some passengers, the plotted distribution represents only those with recorded ages.
Adding survival to the age distribution
The fill aesthetic can also be used with a histogram:
ggplot(titanic, aes(x = Age, fill = Survived)) +
geom_histogram(binwidth = 5) +
labs(
x = "Age",
y = "Passenger count",
title = "Passenger age and survival"
) +
theme_bw()
Now each age interval is divided by survival outcome. This provides more information than the uncolored histogram: it shows how survival counts vary across age groups. The youngest age bins include substantial survival, while older age ranges contain many passengers who died. The display gives support to the idea that age may be related to survival, though it does not by itself isolate age from other factors such as gender and ticket class.
Box-and-whisker plots
A box-and-whisker plot, often called a boxplot, summarizes the distribution of a numeric variable across categories. It can compare ages for passengers who survived and passengers who did not:
ggplot(titanic, aes(x = Survived, y = Age)) +
geom_boxplot() +
labs(
x = "Survival status",
y = "Age",
title = "Age by survival status"
) +
theme_bw()
The horizontal axis divides passengers by survival outcome, while the vertical axis shows age. The box represents the central portion of the distribution, with a line marking the median; the whiskers extend the summary beyond the box. This compact view suggests that survivors tended to be somewhat younger than passengers who died.
A boxplot and a histogram answer related but different questions. The histogram shows how many observations fall in each interval, while the boxplot compresses the distribution into a summary that is easier to compare across groups. Using more than one visualization can give a fuller understanding than relying on a single chart.
Think About It: What detail about age counts is visible in a histogram but not shown directly by a boxplot?
Combining age, gender, class, and survival
The idea of faceting can be applied to numeric data too. A density plot can show the age distribution separately for combinations of gender and ticket class, with survival indicated by fill:
ggplot(titanic, aes(x = Age, fill = Survived)) +
geom_density(alpha = 0.5) +
facet_wrap(~ Sex + Pclass) +
labs(
x = "Age",
y = "Density",
title = "Age and survival by sex and ticket class"
) +
theme_bw()
A density plot is a smoothed representation of a numeric distribution. It serves a role similar to a histogram, but instead of separate bars it shows smooth curves. The alpha setting controls transparency. A value of 0.5 makes the filled areas partly transparent, which helps when colors overlap; opaque areas could obscure one another.
The faceted density plot compares age and survival across combinations of sex and class. It suggests that age alone does not tell the whole story: the relationship between age and survival varies with gender and ticket class. For instance, the youngest passengers appear to have had better survival in some groups, while older male passengers—particularly those in third class—show poor survival. The plot offers a richer picture than examining age, gender, or class separately.
The density plot smooths the data, which can make patterns easier to see but can also hide the exact counts in individual age intervals. A faceted histogram provides a complementary view:
ggplot(titanic, aes(x = Age, fill = Survived)) +
geom_histogram(binwidth = 5) +
facet_wrap(~ Sex + Pclass) +
labs(
x = "Age",
y = "Passenger count",
title = "Passenger age counts by sex and ticket class"
) +
theme_bw()
The histogram makes the number of passengers in each age bin more explicit. Comparing it with the density plot helps distinguish a smooth overall pattern from the underlying binned counts. In this dataset, the combined views show that survival patterns depend on the interaction of age, gender, and class rather than on age in isolation.
A practical way to work with ggplot2
An efficient analysis can proceed in a sequence:
- Understand the fields. Identify what each variable means and whether it is categorical or numeric.
- Choose a question. For example, compare survival across gender or ticket class.
- Map variables to visual properties. Use
x,y, andfillto determine where data appears and how groups are distinguished. - Choose a geometry. Use bars for categorical counts, histograms or density plots for numeric distributions, and boxplots for compact distribution comparisons.
- Add detail as needed. Use labels and themes for clarity, and facets to compare subsets.
- Check the result. Look for missing-value warnings, consider whether the bin width is sensible, and make sure the chart supports the intended interpretation.
Defaults often make it possible to create a useful first chart quickly. More detailed controls become valuable when the chart needs to communicate a particular comparison or meet a specific visual standard. Reusing and adjusting code makes it practical to explore a series of related questions.
Comprehensive review
ggplot2 builds charts by combining data, aesthetic mappings, and geometries, with scales, coordinates, facets, and themes available to control how the result is represented and presented. Correctly identifying categorical variables such as survival, sex, and ticket class is essential because their digits may look numeric even though they are labels rather than measurements.
Bar charts make categorical counts and their composition visible. Histograms and density plots reveal numeric distributions, while boxplots summarize and compare those distributions. fill can distinguish categories within a chart, and faceting separates subsets into panels so patterns can be compared without collapsing them together. Labels, themes, and thoughtful bin widths improve readability, while missing-value warnings remind the analyst which observations a chart excludes.
Across the Titanic example, visualizations suggest that survival varied with gender, ticket class, and age. The strongest interpretation comes from comparing several views: a single chart can reveal a useful pattern, while complementary charts help explain how that pattern changes across groups.

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