Chapter 3 Data Visualisation

Take the quiz to see if you need to review this chapter.

3.1 Learning Objectives

3.1.1 Basic

  1. Understand what types of graphs are best for different types of data
    • 1 discrete
    • 1 continuous
    • 2 discrete
    • 2 continuous
    • 1 discrete, 1 continuous
    • 3 continuous
  2. Create common types of graphs with ggplot2
  3. Set custom labels and colours
  4. Represent factorial designs with different colours or facets
  5. Save plots as an image file

3.1.2 Intermediate

  1. Superimpose different types of graphs
  2. Add lines to graphs
  3. Deal with overlapping data
  4. Create less common types of graphs

3.1.3 Advanced

  1. Arrange plots in a grid using cowplot
  2. Adjust axes (e.g., flip coordinates, set axis limits)
  3. Change the theme
  4. Create interactive graphs with plotly

3.3 Common Variable Combinations

Continuous variables are properties you can measure, like height. Discrete (or categorical) variables are things you can count, like the number of pets you have. Categorical variables can be nominal, where the categories don’t really have an order, like cats, dogs and ferrets (even though ferrets are obviously best). They can also be ordinal, where there is a clear order, but the distance between the categories isn’t something you could exactly equate, like points on a Likert rating scale.

Different types of visualisations are good for different types of variables.

Before you read ahead, come up with an example of each type of variable combination and sketch the types of graphs that would best display these data.

  • 1 discrete
  • 1 continuous
  • 2 discrete
  • 2 continuous
  • 1 discrete, 1 continuous
  • 3 continuous

3.3.1 Data

The code below creates some data frames with different types of data. We’ll learn how to simulate data like this in the Probability & Simulation chapter, but for now just run the code chunk below.

  • pets has a column with pet type
  • pet_happy has happiness and age for 500 dog owners and 500 cat owners
  • x_vs_y has two correlated continuous variables (x and y)
  • overlap has two correlated ordinal variables and 1000 observations so there is a lot of overlap
  • overplot has two correlated continuous variables and 10000 observations

First, think about what kinds of graphs are best for representing these different types of data.

3.4 Basic Plots

3.4.1 Bar plot

Bar plots are good for categorical data where you want to represent the count.

Bar plot

Figure 3.1: Bar plot

3.4.2 Density plot

Density plots are good for one continuous variable, but only if you have a fairly large number of observations.

Density plot

Figure 3.2: Density plot

You can represent subsets of a variable by assigning the category variable to the argument group, fill, or color.

Grouped density plot

Figure 3.3: Grouped density plot

Try changing the alpha argument to figure out what it does.

3.4.3 Frequency Polygons

If you don’t want smoothed distributions, try geom_freqpoly().

Frequency ploygon plot

Figure 3.4: Frequency ploygon plot

Try changing the binwidth argument to 5 and 0.1. How do you figure out the right value?

3.4.4 Histogram

Histograms are also good for one continuous variable, and work well if you don’t have many observations. Set the binwidth to control how wide each bar is.

Histogram

Figure 3.5: Histogram

Histograms in ggplot look pretty bad unless you set the fill and color.

If you show grouped histograms, you also probably want to change the default position argument.

Grouped Histogram

Figure 3.6: Grouped Histogram

Try changing the position argument to “identity”, “fill”, “dodge”, or “stack”.

3.4.5 Column plot

Column plots are the worst way to represent grouped continuous data, but also one of the most common.

To make column plots with error bars, you first need to calculate the means, error bar uper limits (ymax) and error bar lower limits (ymin) for each category. You’ll learn more about how to use the code below in the next two lessons.

Column plot

Figure 3.7: Column plot

What do you think geom_hline() does?

3.4.6 Boxplot

Boxplots are great for representing the distribution of grouped continuous variables. They fix most of the problems with using barplots for continuous data.

Box plot

Figure 3.8: Box plot

3.4.7 Violin plot

Violin pots are like sideways, mirrored density plots. They give even more information than a boxplot about distribution and are especially useful when you have non-normal distributions.

Violin plot

Figure 3.9: Violin plot

Try changing the numbers in the draw_quantiles argument.

3.4.8 Scatter plot

Scatter plots are a good way to represent the relationship between two continuous variables.

Scatter plot using geom_point()

Figure 3.10: Scatter plot using geom_point()

3.4.9 Line graph

You often want to represent the relationship as a single line.

Line plot using geom_smooth()

Figure 3.11: Line plot using geom_smooth()

3.5 Customisation

3.5.1 Labels

You can set custom titles and axis labels in a few different ways.

Set custom labels with ggtitle(), xlab() and ylab()

Figure 3.12: Set custom labels with ggtitle(), xlab() and ylab()

Set custom labels with labs()

Figure 3.13: Set custom labels with labs()

3.5.2 Colours

You can set custom values for colour and fill using functions like scale_colour_manual() and scale_fill_manual(). The Colours chapter in Cookbook for R has many more ways to customise colour.

Set custom colour

Figure 3.14: Set custom colour

3.5.3 Save as File

You can save a ggplot using ggsave(). It saves the last ggplot you made, by default, but you can specify which plot you want to save if you assigned that plot to a variable.

You can set the width and height of your plot. The default units are inches, but you can change the units argument to “in”, “cm”, or “mm”.

3.6 Combination Plots

3.6.1 Violinbox plot

To demonstrate the use of facet_grid() for factorial designs, we create a new column called agegroup to split the data into participants older than the meadian age or younger than the median age. New factors will display in alphabetical order, so we can use the factor() function to set the levels in the order we want.

Violin-box plot

Figure 3.15: Violin-box plot

Set the show.legend argument to FALSE to hide the legend. We do this here because the x-axis already labels the pet types.

3.6.2 Violin-point-range plot

You can use stat_summary() to superimpose a point-range plot showning the mean ± 1 SD. You’ll learn how to write your own functions in the lesson on Iteration and Functions.

Point-range plot using stat_summary()

Figure 3.16: Point-range plot using stat_summary()

3.6.4 Scatter-line graph

If your graph isn’t too complicated, it’s good to also show the individual data points behind the line.

Scatter-line plot

Figure 3.18: Scatter-line plot

3.7 Overlapping Discrete Data

3.7.1 Reducing Opacity

You can deal with overlapping data points (very common if you’re using Likert scales) by reducing the opacity of the points. You need to use trial and error to adjust these so they look right.

Deal with overlapping data using transparency

Figure 3.20: Deal with overlapping data using transparency

3.7.2 Proportional Dot Plots

Or you can set the size of the dot proportional to the number of overlapping observations using geom_count().

Deal with overlapping data using geom_count()

Figure 3.21: Deal with overlapping data using geom_count()

Alternatively, you can transform your data to create a count column and use the count to set the dot colour.

Deal with overlapping data using dot colour

Figure 3.22: Deal with overlapping data using dot colour

The viridis package changes the colour themes to be easier to read by people with colourblindness and to print better in greyscale. Viridis is built into ggplot2 since v3.0.0. It uses scale_colour_viridis_c() and scale_fill_viridis_c() for continuous variables and scale_colour_viridis_d() and scale_fill_viridis_d() for discrete variables.

3.8 Overlapping Continuous Data

Even if the variables are continuous, overplotting might obscure any relationships if you have lots of data.

Overplotted data

Figure 3.23: Overplotted data

3.8.1 2D Density Plot

Use geom_density2d() to create a contour map.

Contour map with geom_density2d()

Figure 3.24: Contour map with geom_density2d()

You can use stat_density_2d(aes(fill = ..level..), geom = "polygon") to create a heatmap-style density plot.

Heatmap-density plot

Figure 3.25: Heatmap-density plot

3.8.2 2D Histogram

Use geom_bin2d() to create a rectangular heatmap of bin counts. Set the binwidth to the x and y dimensions to capture in each box.

Heatmap of bin counts

Figure 3.26: Heatmap of bin counts

3.8.3 Hexagonal Heatmap

Use geomhex() to create a hexagonal heatmap of bin counts. Adjust the binwidth, xlim(), ylim() and/or the figure dimensions to make the hexagons more or less stretched.

Hexagonal heatmap of bin counts

Figure 3.27: Hexagonal heatmap of bin counts

3.8.4 Correlation Heatmap

I’ve included the code for creating a correlation matrix from a table of variables, but you don’t need to understand how this is done yet. We’ll cover mutate() and gather() functions in the dplyr and tidyr lessons.

Once you have a correlation matrix in the correct (long) format, it’s easy to make a heatmap using geom_tile().

Heatmap using geom_tile()

Figure 3.28: Heatmap using geom_tile()

The file type is set from the filename suffix, or by specifying the argument device, which can take the following values: “eps”, “ps”, “tex”, “pdf”, “jpeg”, “tiff”, “png”, “bmp”, “svg” or “wmf”.

3.9 Interactive Plots

You can use the plotly package to make interactive graphs. Just assign your ggplot to a variable and use the function ggplotly().

Figure 3.29: Interactive graph using plotly

Hover over the data points above and click on the legend items.

3.10 Quiz

  1. Generate a plot like this from the built-in dataset iris. Make sure to include the custom axis labels.

  2. You have just created a plot using the following code. How do you save it?

  3. Debug the following code.

  4. Generate a plot like this from the built-in dataset ChickWeight.

  5. Generate a plot like this from the built-in dataset iris.

3.11 Exercises

Download the exercises. See the plots to see what your plots should look like (this doesn’t contain the answer code). See the answers only after you’ve attempted all the questions.