1. Home
  2. Explore
  3. Statistics
  4. Data Visualization with R

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Data Visualization with R

Speaker 1Speaker 2

Data Visualization with R

12:30
0:00-12:30
  1. Hope

    Welcome to our introduction to data visualization with R and ggplot2. We’ll follow a data scientist investigating the Titanic passenger data, and focus on a practical set of ggplot2 tools: enough to build clear visualizations and explore useful questions without trying to cover every advanced feature.

  2. Anna

    And the audience in our scenario matters. The consulting data scientist needs to explain patterns to business stakeholders who may not be comfortable with statistics, so intuitive charts are more useful as a starting point than a wall of summary numbers.

  3. Hope

    The tutorial assumes you can read and work with basic R code, and already know what charts such as histograms and box-and-whisker plots are. The focus is how to make those charts with ggplot2, not teaching R syntax or the underlying theory of each chart.

  4. Anna

    To follow along, you need R and the ggplot2 package; RStudio is optional, but recommended. The webinar’s GitHub materials include the code, data, and slides. The presenter also points to Hadley Wickham’s ggplot2 book as a strong resource for beginners and experienced users alike.

  5. Hope

    Why use Titanic data? The story is familiar to a broad audience, which helps people from different backgrounds engage with the analysis. It also resembles business data: it can be imperfect, and some columns bundle together more than one meaning—features analysts often encounter in customer data.

  6. Anna

    The central question is: who survived, who did not, and what patterns might help explain the outcomes? Before we visualize, let’s make sure we understand what the columns mean, because choosing a chart depends on understanding the data behind it.

  7. Hope

    The outcome, survived, is zero for a passenger who perished and one for someone who survived. Pclass records ticket class—first, second, or third—and sex records male or female. Age is numeric and can include decimal values.

  8. Anna

    There are also two overloaded family columns. SibSp counts siblings and/or a spouse traveling with the passenger, while Parch counts parents and/or children. Ticket is the ticket’s serial number, fare is the price in pounds sterling, cabin is present for only some passengers, and embarked records a port: Cherbourg, Queenstown, or Southampton.

  9. Hope

    The data has 891 observations and 12 columns. Passenger ID and name are additional columns beyond the dictionary we just described. In this dataset each ID and each name is unique, so in its current form neither provides an obvious analytical pattern for this investigation. Text analysis might extract information from names, but that’s outside today’s scope.

  10. Anna

    One important preparation step is to distinguish numeric measurements from categories. R may read survived and pclass as numbers, but we aren’t going to multiply or divide survival codes, or interpret third class as three times first class. Treat survived, pclass, sex, and embarked as categorical factors instead.

  11. Hope

    That choice matters because ggplot2 can use categories in useful ways, including to color-code a chart. Age, by contrast, is numeric. The data also has missing ages; we’ll keep that in mind when we make plots.

  12. Anna

    Now, what is ggplot2? Its name refers to the grammar of graphics. It’s become a widely used visualization tool in the R community because it can produce polished graphics with relatively little code, while also allowing detailed control when you want to customize the result.

  13. Hope

    That combination can sound contradictory: powerful, but also easy to start with. The key is that most of the time ggplot2’s defaults are useful. You can begin with a small amount of code, then add more detail only when you need a particular adjustment.

  14. Anna

    The full grammar has six parts. Data is the raw material, and layers are the visible marks—such as bars, points, and lines. Scales map data values into the available visual space, while coordinates set the plot’s perspective; the familiar two-dimensional x-y grid is the common default.

  15. Hope

    The other two parts are faceting and themes. Faceting splits a visualization into panels so you can compare subsets of data, much like looking at a chart after drilling down through categories. Themes control presentation details such as fonts, sizes, and colors.

  16. Anna

    But to get started, you usually need just three things: the data, aesthetic mappings, and a layer. An aesthetic mapping—often written with the function aes—says which data variables should map to visual properties, such as putting age on the x-axis.

  17. Hope

    Then you choose a layer to tell ggplot2 what to draw. These layer functions begin with geom, short for geometry: geom_bar makes a bar chart, geom_histogram makes a histogram, and there are many other choices. Put together, the basic idea is: here’s my data, map these variables, and draw this kind of chart.

  18. Anna

    Let’s apply that to the first question: what was the overall survival rate? Since survived is categorical, a bar chart is a natural first view. Mapping survived to the x-axis and adding a bar layer gives a count for each category.

  19. Hope

    The chart shows more passengers perished than survived. We can estimate the proportions visually, but if we want exact percentages, the tutorial suggests calculating them separately rather than adding more advanced labeling code. The proportions are about 62 percent who perished and 38 percent who survived.

  20. Anna

    We can improve the chart for an audience by adding a descriptive y-axis label and a title with labs. The speaker also prefers a clean white background, which can be set with a theme. A useful workflow is to copy the basic plot and reuse it, changing only the mappings or labels needed for the next question.

  21. Hope

    Next, consider the idea of ‘women and children first.’ First we can examine sex. Keep survived as the fill aesthetic, and map sex to the x-axis. Because survived is categorical, the bars are color-coded to show the counts of passengers who survived and those who perished within each sex.

  22. Anna

    That chart makes the contrast easy to see: most males in the dataset perished, while most females survived. It also shows that there were more males aboard—roughly twice as many as females. The visual comparison helps tell the story without asking the audience to interpret a table of figures.

  23. Hope

    That’s evidence consistent with the ‘women and children first’ idea, but gender may not be the only factor. Ticket class is another question to explore. Replace sex with pclass on the x-axis and keep the survival fill, then compare the survival proportions across first, second, and third class.

  24. Anna

    The chart suggests that survival rates declined by class: more than half of first-class passengers survived, second class was around half, and third class was closer to one in four. It also shows counts, and those counts aren’t simply a neat progression: in this dataset there were fewer second-class passengers than either first- or third-class passengers.

  25. Hope

    To explore sex and class together, use faceting. With pclass as the facet variable, ggplot2 creates a panel for each class, and each panel can compare female and male passengers with the same survival colors. Faceting is a visual drill-down: it lets us compare subsets while keeping a consistent chart form.

  26. Anna

    The panels sharpen the pattern. Females in first and second class overwhelmingly survived; females in third class had a more even split. Males had substantially lower survival across the classes, and the chart suggests first-class males did best among men, with third-class males doing worst.

  27. Hope

    The panels also reveal different numbers of males and females by class. The imbalance is especially visible in third class, where there were many more males than females. That may be worth investigating further, even if our main question here is survival.

  28. Anna

    Now let’s examine age, the other part of our starting hypothesis. A histogram is a useful way to see the distribution of a numeric variable. In ggplot2, use age on the x-axis and a histogram layer; the bin width determines how ages are grouped.

  29. Hope

    For example, a bin width of five groups ages into five-year intervals. A different width changes the shape and detail of the histogram, so it’s worth trying sensible alternatives and deciding which best represents the data. In this example, five years is the chosen width.

  30. Anna

    When ggplot2 encounters the missing age values, it removes them from the histogram and reports how many were missing—177 here. That lets us make the chart using available ages, while reminding us that missing values may require attention in a fuller analysis.

  31. Hope

    The age distribution has a long tail toward older passengers, with people as old as 80. There are some children, but the largest concentration is around ages 20 to 40. Add survived as the fill aesthetic, and the histogram also shows survival versus death within each age bin.

  32. Anna

    That filled histogram offers support for the children part of the hypothesis: in the youngest age groups, more than half survived. At older ages, the chart generally shows a larger share who perished. Looking at the bars together gives a more detailed age-based picture than the overall survival chart.

  33. Hope

    Another view of age is a box-and-whisker plot. Put survived on the x-axis and age on the y-axis, and compare the age distributions for those who perished and those who survived. The plot suggests that survivors tended to be somewhat younger, but the difference is not dramatic.

  34. Anna

    And that’s why it helps to use more than one visualization. The box plot gives a compact comparison of distributions, while the filled histogram makes the especially young age groups easier to inspect. Each chart highlights different aspects of the data.

  35. Hope

    We can combine the age question with the earlier class-and-sex comparison by faceting on both sex and pclass. A density plot displays a smoothed view of a distribution, analogous to a histogram. Setting alpha, or transparency, allows overlapping colored areas to remain visible.

  36. Anna

    This view suggests that age does not act alone: survival patterns vary with age, sex, and class together. The charts show especially strong survival among younger passengers in some groups, including children in second class, and a poor pattern for older males, particularly in third class.

  37. Hope

    Because density plots smooth the data, they can make some details harder to judge. A faceted histogram using the same age, sex, class, and survival breakdown is a useful companion. The histogram makes individual age bins more visible, and the example suggests strong survival among girls and boys in some classes, alongside poor survival for older males in third class.

  38. Anna

    The larger lesson is to compare views rather than trusting one plot to tell the whole story. Histograms, density plots, and box plots each show age differently, while faceting makes it possible to compare relevant groups. Together, they help us explain the patterns without overstating what any single chart can establish.

  39. Hope

    So our practical ggplot2 recipe is simple: understand and prepare the data, map variables to visual properties, choose a geom, and add labels, themes, or facets when they help answer the question. The grammar gives you room for detailed customization, but you can do a lot with the essentials and the defaults.

  40. Anna

    And in this example, those essentials helped us move from overall survival to comparisons by sex, class, and age. The plots make the patterns easier to discuss with a nontechnical audience, while leaving further analysis—such as investigating missing ages or extracting signal from names—open for later.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent