Chapter 3 – Plotting Two Variables (1)

After learning to plot a single variable in the previous chapter, we now turn to plotting two variables.

For those of you in sociology 1205, this chapter covers the EDA module for unit 3. You will find the tutorial scripts in your R Studio Cloud workspace.

But we are also going to do a little more than just plotting. We are also going to learn how to use different color palettes to help us extract information from our plots more easily. This chapter includes a short lecture and three tutorials.

The first tutorial focuses on plotting two categorical variables, manipulating those plots for better understanding of our data, as well as using new color palettes. The second tutorial focuses on plotting a numeric and a categorical variable as well as introduces the concept of faceting. We examine the same topics in tutorial 3 with a different dataset.

Learning Objectives

In this chapter, we will cover the following topics:

  • how to plot two categorical variables;
  • how to plot one numeric variable and one categorical variable;
  • how to load and use color palettes;
  • how to facet a numeric variable by the levels of one categorical variable.

Introduction to color palettes

Tutorial 1 – Part 1

Tutorial 1 – Part 2

Tutorial 1  – Part 3

Tutorial 2 – Part 1

Tutorial 2 – Part 2

Tutorial 3 – Part 1

Tutorial 3 – Part 2

Key functions used in this chapter

  • table(): the function that tabulates variables;
  • scale_fill_brewer(): the function that fills a variable with a brewer palette;
  • scale_fill_jcolors(): the function that fills a variable with a jcolors palette;
  • scale_fill_viridis(): the function that fills a variable with a viridis palette;
  • coord_flip(): the function that flips the orientation of a plot (for instance, from vertical to horizontal);
  • geom_mosaic(): the function, out of the ggmosaic library, that creates a mosaic plot;
  • facet_wrap(): the function that facets a numeric variable by the levels of a categorical / factor variable;
  • scale_fill_binned(): the function that assigns discrete color palettes to a numeric variable;

Before moving on to the next chapter, or for those of you in Sociology 1205, the exercise, test your understanding with the quiz below:

License

Icon for the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License

Visualizing Data with R Copyright © 2022 by Christine Monnier is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License, except where otherwise noted.

Share This Book