Creating a faceted bar graph
This recipe will create a faceted bar graph using the Titanic dataset. This particular set comes from base R packages, but it's not a data frame. To plot this data using ggplot2
, we first need to to coerce this object to a data frame. Recipe will introduce the faceting function.
The goal here is to make a plot showing how many people survived and how many died in the Titanic tragedy. Facets are used to split this analysis both by gender (male and female) and age range (child or adult). There are no prior requirements other than ggplot2
and plotly
packages installed.
How to do it...
This section shows you how to create a faceted bar graph:
- Coerce the
Titanic
table to the data frame type:
> data_titanic <- as.data.frame(Titanic)
- Load
ggplot2
, design a bar graph, and add the facets usingface_grid()
function:
> library(ggplot2) > bar <- ggplot(data_titanic, aes(x = Survived)) + geom_bar(aes(fill = Survived, weight = Freq)) + facet_grid(Sex ~ Age...