{ "metadata": {}, "nbformat": 4, "nbformat_minor": 5, "cells": [ { "id": "metadata", "cell_type": "markdown", "source": "
\n\n# Data visualisation Olympics - Visualization in R\n\nby [The Carpentries](https://training.galaxyproject.org/hall-of-fame/carpentries/)\n\nCC-BY licensed content from the [Galaxy Training Network](https://training.galaxyproject.org/)\n\n**Objectives**\n\n- How does plotting work in R?\n- How can I facet plots?\n- How do I produce a nice, publication ready plot with ggplot2?\n\n**Objectives**\n\n- Produce scatter plots, boxplots, and time series plots using ggplot.\n- Set universal plot settings.\n- Describe what faceting is and apply faceting in ggplot.\n- Modify the aesthetics of an existing ggplot plot (including axis labels and color).\n- Build complex and customized plots from data in a data frame.\n\n**Time Estimation: 1h**\n
\n", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-0", "source": "

In this tutorial, you will learn how to produce scatter plots, boxplots, and time series plots using ggplot. You will also learn how to set universal plot settings, modify the aesthetics of an existing ggplot plots (including axis labels and color), and learn how to facet in ggplot.

\n
\n
Comment
\n

This tutorial is significantly based on Data Carpentry lesson “Data visualization with ggplot2”.

\n
\n
\n
Agenda
\n

In this tutorial, we will cover:

\n
    \n
  1. Background
      \n
    1. Data Visualization with ggplot2
    2. \n
    \n
  2. \n
\n
\n

Background

\n

In this tutorial, we will use as our dataset a table with results from the Olympics, from the games in Athens in 1896 until Tokyo in 2020. The objective is to familiarize you with a large number of the most important data visualisation tools in Galaxy. Much like the Olympics, there are many different disciplines (types of operations), and for each operation there are often multiple techniques (tools) available to athletes (data analysts, you) that are great for achieving the goal.

\n

\"image

\n

We will show you many of these commonly needed visualisation operations, and some examples of how to perform them in R. We also provide many exercises so that you can train your skills and become a data visualisation Olympian!

\n

Data Visualization with ggplot2

\n

We start by loading the required packages. ggplot2 is included in the tidyverse package.

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-1", "source": [ "library(tidyverse)" ], "cell_type": "code", "execution_count": null, "outputs": [], "metadata": { "attributes": { "classes": [ "> " ], "id": "" } } }, { "id": "cell-2", "source": "

Download Data

\n

Before we can do any visualisation, we will need some data. Let’s download our table with Olympics results now.

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-3", "source": [ "olympics <- read_tsv(\"https://zenodo.org/record/6803028/files/olympics.tsv\")" ], "cell_type": "code", "execution_count": null, "outputs": [], "metadata": { "attributes": { "classes": [ "> " ], "id": "" } } }, { "id": "cell-4", "source": "\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-5", "source": [ "View(olympics)" ], "cell_type": "code", "execution_count": null, "outputs": [], "metadata": { "attributes": { "classes": [ "> " ], "id": "" } } }, { "id": "cell-6", "source": "
\n
Question
\n
    \n
  1. What is the format of the file?
  2. \n
  3. How is it structured?
  4. \n
  5. How many lines are in the file?
  6. \n
  7. How many columns?
  8. \n
\n
👁 View solution\n
\n
    \n
  1. When you expand the olympics.tsv dataset in your history (see also screenshot below), you will see format: tabular, this is another term for a tab-separated (tsv) file.
  2. \n
  3. Each row represents an athlete’s participation in an event. If an athlete competes in multiple events, there is a line for each event.
  4. \n
  5. 234,522. Look at the bottom of the View or Environment panels to see this number.
  6. \n
  7. There are 17 columns in this file. See View or Environment panels.
  8. \n
\n
\n
\n

About this dataset

\n

The data was obtained from Olympedia. The file olympics.tsv contains\n234,522 rows and 17 columns. Each row corresponds to an individual athlete competing in an individual Olympic event. The columns are:

\n\n

We will use this dataset to practice our data visualisation skills in Galaxy.

\n

Plotting with ggplot2

\n

ggplot2 is a plotting package that provides helpful commands to create complex plots\nfrom data in a data frame. It provides a more programmatic interface for\nspecifying what variables to plot, how they are displayed, and general visual\nproperties. Therefore, we only need minimal changes if the underlying data\nchange or if we decide to change from a bar plot to a scatterplot. This helps in\ncreating publication quality plots with minimal amounts of adjustments and\ntweaking.

\n

ggplot2 refers to the name of the package itself. When using the package we use the\nfunction ggplot() to generate the plots, and so references to using the function will\nbe referred to as ggplot() and the package as a whole as ggplot2

\n

ggplot2 plots work best with data in the ‘long’ format, i.e., a column for every variable,\nand a row for every observation. Well-structured data will save you lots of time\nwhen making figures with ggplot2

\n

ggplot graphics are built layer by layer by adding new elements. Adding layers in\nthis fashion allows for extensive flexibility and customization of plots.

\n

To build a ggplot, we will use the following basic template that can be used for different types of plots:

\n
ggplot(data = <DATA>, mapping = aes(<MAPPINGS>)) +  <GEOM_FUNCTION>()\n
\n

use the ggplot() function and bind the plot to a specific data frame using the data argument

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-7", "source": [ "ggplot(data = olympics)" ], "cell_type": "code", "execution_count": null, "outputs": [], "metadata": { "attributes": { "classes": [ "> " ], "id": "" } } }, { "id": "cell-8", "source": "\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-9", "source": [ "ggplot(data = olympics, mapping = aes(x = year, y = height))" ], "cell_type": "code", "execution_count": null, "outputs": [], "metadata": { "attributes": { "classes": [ "> " ], "id": "" } } }, { "id": "cell-10", "source": "\n

To add a geom to the plot use + operator. Because we have two continuous\nvariables, let’s use geom_point() first:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-11", "source": [ "ggplot(data = olympics, aes(x = year, y = height)) +\n", " geom_point()" ], "cell_type": "code", "execution_count": null, "outputs": [], "metadata": { "attributes": { "classes": [ "> " ], "id": "" } } }, { "id": "cell-12", "source": "

The + in the ggplot2 package is particularly useful because it allows\nyou to modify existing ggplot objects. This means you can easily set up plot\n“templates” and conveniently explore different types of plots, so the above\nplot can also be generated with code like this:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-13", "source": [ "# Assign plot to a variable\n", "height_plot <- ggplot(data = olympics,\n", " mapping = aes(x = year, y = height))\n", "\n", "# Draw the plot\n", "height_plot +\n", " geom_point()" ], "cell_type": "code", "execution_count": null, "outputs": [], "metadata": { "attributes": { "classes": [ "> " ], "id": "" } } }, { "id": "cell-14", "source": "\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-15", "source": [ "## Create a ggplot and draw it.\n", "height_plot <- ggplot(data = olympics,\n", " aes(x = year, y = height))\n", "\n", "height_plot +\n", " geom_point()" ], "cell_type": "code", "execution_count": null, "outputs": [], "metadata": { "attributes": { "classes": [ "> " ], "id": "" } } }, { "id": "cell-16", "source": "

Notes

\n\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-17", "source": [ "# This is the correct syntax for adding layers\n", "height_plot +\n", " geom_point()\n", "\n", "# This will not add the new layer and will return an error message\n", "# height_plot\n", "# + geom_point()" ], "cell_type": "code", "execution_count": null, "outputs": [], "metadata": { "attributes": { "classes": [ "> " ], "id": "" } } }, { "id": "cell-18", "source": "
\n
Challenge (optional)
\n

Scatter plots can be useful exploratory tools for small datasets. For data\nsets with large numbers of observations, such as the olympics data\nset, overplotting of points can be a limitation of scatter plots. One strategy\nfor handling such settings is to use hexagonal binning of observations. The\nplot space is tessellated into hexagons. Each hexagon is assigned a color\nbased on the number of observations that fall within its boundaries. To use\nhexagonal binning with ggplot2, first install the R package hexbin\nfrom CRAN:

\n
# install.packages(\"hexbin\")\nlibrary(hexbin)\n
\n

Then use the geom_hex() function:

\n
height_plot +\n geom_hex()\n
\n

What are the relative strengths and weaknesses of a hexagonal bin plot\ncompared to a scatter plot? Examine the above scatter plot and compare it\nwith the hexagonal bin plot that you created.

\n
\n

Data Cleaning & Calculations

\n

We’ll calculate some new fields to enable us to answer more questions, let’s do that now.

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-19", "source": [ "olympics <- olympics %>%\n", " mutate(age = year - birth_year) %>%\n", " mutate(weight = as.integer(weight)) %>%\n", " filter(!is.na(weight)) %>%\n", " filter(!is.na(height))" ], "cell_type": "code", "execution_count": null, "outputs": [], "metadata": { "attributes": { "classes": [ "> " ], "id": "" } } }, { "id": "cell-20", "source": "

And to speed up future plots, let’s pick three countries and three sports we’re\ninterested in to reduce the amount of data we’ll need to plot:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-21", "source": [ "sports = c(\"Archery\", \"Judo\", \"Speed Skating\")\n", "# You can change this to any of:\n", "# c(\"Alpine Skiing\", \"Archery\", \"Art Competitions\", \"Artistic Gymnastics\", \"Artistic Swimming\", \"Athletics\", \"Badminton\", \"Baseball\", \"Basketball\", \"Biathlon\", \"Bobsleigh\", \"Bowling\", \"Boxing\", \"Canoe Marathon\", \"Canoe Slalom\", \"Canoe Sprint\", \"Cross Country Skiing\", \"Cycling BMX Freestyle\", \"Cycling BMX Racing\", \"Cycling Mountain Bike\", \"Cycling Road\", \"Cycling Track\", \"Diving\", \"Dogsled Racing\", \"Equestrian Dressage\", \"Equestrian Eventing\", \"Equestrian Jumping\", \"Fencing\", \"Figure Skating\", \"Freestyle Skiing\", \"Golf\", \"Handball\", \"Hockey\", \"Judo\", \"Karate\", \"Luge\", \"Marathon Swimming\", \"Military Ski Patrol\", \"Modern Pentathlon\", \"Nordic Combined\", \"Rhythmic Gymnastics\", \"Rowing\", \"Rugby\", \"Sailing\", \"Shooting\", \"Short Track Speed Skating\", \"Skateboarding\", \"Skeleton\", \"Ski Jumping\", \"Snowboarding\", \"Speed Skating\", \"Speed Skiing\", \"Surfing\", \"Swimming\", \"Table Tennis\", \"Taekwondo\", \"Tennis\", \"Trampolining\", \"Triathlon\", \"Tug-Of-War\", \"Volleyball\", \"Water Polo\", \"Weightlifting\", \"Winter Pentathlon\", \"Wrestling\", \"Wushu\")\n", "\n", "countries = c(\"NED\", \"USA\", \"CHN\")\n", "\n", "olympics_small <- olympics %>% filter(sport %in% sports) %>% filter(noc %in% countries)" ], "cell_type": "code", "execution_count": null, "outputs": [], "metadata": { "attributes": { "classes": [ "> " ], "id": "" } } }, { "id": "cell-22", "source": "

Building your plots iteratively

\n

Building plots with ggplot2 is typically an iterative process. We start by\ndefining the dataset we’ll use, lay out the axes, and choose a geom:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-23", "source": [ "ggplot(olympics_small, aes(x=age, y=sport)) +\n", " geom_point()" ], "cell_type": "code", "execution_count": null, "outputs": [], "metadata": { "attributes": { "classes": [ "> " ], "id": "" } } }, { "id": "cell-24", "source": "

Then, we start modifying this plot to extract more information from it. For\ninstance, we can add transparency (alpha) to avoid overplotting:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-25", "source": [ "ggplot(olympics_small, aes(x=age, y=sport)) +\n", " geom_point(alpha = 0.1)" ], "cell_type": "code", "execution_count": null, "outputs": [], "metadata": { "attributes": { "classes": [ "> " ], "id": "" } } }, { "id": "cell-26", "source": "

We can also add colors for all the points:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-27", "source": [ "ggplot(olympics_small, aes(x=age, y=sport)) +\n", " geom_point(alpha = 0.1, color = \"blue\")" ], "cell_type": "code", "execution_count": null, "outputs": [], "metadata": { "attributes": { "classes": [ "> " ], "id": "" } } }, { "id": "cell-28", "source": "

Or to color each species in the plot differently, you could use a vector as an input to the argument color. ggplot2 will provide a different color corresponding to different values in the vector. Here is an example where we color with species_id:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-29", "source": [ "ggplot(olympics_small, aes(x=age, y=sport)) +\n", " geom_point(alpha = 0.1, aes(color = sex))" ], "cell_type": "code", "execution_count": null, "outputs": [], "metadata": { "attributes": { "classes": [ "> " ], "id": "" } } }, { "id": "cell-30", "source": "
\n
Challenge
\n

Use what you just learned to create a scatter plot of height over\nsport with the plot types showing the season in different colors.\nIs this a good way to show this type of data?

\n
👁 View solution\n
\n
ggplot(data = olympics,\n       mapping = aes(x = height, y = sport)) +\n   geom_point(aes(color = season))\n
\n
\n
\n

Boxplot

\n

We can use boxplots to visualize the distribution of height within each sport:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-31", "source": [ "ggplot(data = olympics_small, mapping = aes(x = height, y = sport)) +\n", " geom_boxplot()" ], "cell_type": "code", "execution_count": null, "outputs": [], "metadata": { "attributes": { "classes": [ "> " ], "id": "" } } }, { "id": "cell-32", "source": "

But this is a bit boring with all three merged together, so let’s colour by NOC.

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-33", "source": [ "ggplot(olympics_small, aes(x = height, y = sport, fill=noc)) +\n", " geom_boxplot()" ], "cell_type": "code", "execution_count": null, "outputs": [], "metadata": { "attributes": { "classes": [ "> " ], "id": "" } } }, { "id": "cell-34", "source": "

By adding points to the boxplot, we can have a better idea of the number of\nmeasurements and of their distribution. Because the boxplot will show the outliers\nby default these points will be plotted twice – by geom_boxplot and\ngeom_jitter. To avoid this we must specify that no outliers should be added\nto the boxplot by specifying outlier.shape = NA.

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-35", "source": [ "ggplot(olympics_small, aes(x = height, y = sport, fill=noc)) +\n", " geom_boxplot(outlier.shape = NA) +\n", " geom_jitter(alpha = 0.3, color = \"orange\")" ], "cell_type": "code", "execution_count": null, "outputs": [], "metadata": { "attributes": { "classes": [ "> " ], "id": "" } } }, { "id": "cell-36", "source": "

Notice how the boxplot layer is behind the jitter layer? What do you need to\nchange in the code to put the boxplot in front of the points such that it’s not\nhidden?

\n
\n
Challenge
\n

Boxplots are useful summaries, but hide the shape of the distribution. For\nexample, if there is a bimodal distribution, it would not be observed with a\nboxplot. An alternative to the boxplot is the violin plot (sometimes known as\na beanplot), where the shape (of the density of points) is drawn.

\n\n
👁 View solution\n
\n
ggplot(olympics_small, aes(x = height, y = sport)) +\n    geom_jitter(alpha = 0.3, color = \"orange\") +\n    geom_violin()\n
\n
\n
\n

In many types of data, it is important to consider the scale of the\nobservations. For example, it may be worth changing the scale of the axis to\nbetter distribute the observations in the space of the plot. Changing the scale\nof the axes is done similarly to adding/modifying other components (i.e., by\nincrementally adding commands). Try making these modifications:

\n\n
👁 View solution\n
\n
ggplot(olympics_small, aes(x = height, y = sport)) +\nscale_x_log10() +\ngeom_jitter(alpha = 0.3, color = \"orange\") +\ngeom_boxplot(outlier.shape = NA)\n
\n\n

So far, we’ve looked at the distribution of height within specific sports. Try making\na new plot to explore the distribution of another variable within each sport!

\n

Create boxplot for age by sport. Overlay the boxplot layer on a jitter\nlayer to show actual measurements.

\n
👁 View solution\n
\n
ggplot(olympics_small, aes(x = age, y = sport)) +\ngeom_jitter(alpha = 0.3, color = \"orange\") +\ngeom_boxplot(outlier.shape = NA)\n
\n\n

Add color to the data points on your boxplot according to the year from which\nthe sample was taken (year).

\n

Hint: Check the class for year. Consider changing the class of year\nfrom integer to factor. Why does this change how R makes the graph?

\n
👁 View solution\n
\n
ggplot(olympics_small, aes(x = age, y = sport)) +\n  geom_jitter(alpha = 0.3, aes(color=year)) +\n  geom_boxplot(outlier.shape = NA)\n\n# As a factor:\nggplot(olympics_small, aes(x = age, y = sport)) +\n  geom_jitter(alpha = 0.3, aes(color=as.factor(year))) +\n  geom_boxplot(outlier.shape = NA)\n
\n\n

Plotting time series data

\n

Let’s calculate number of participants per year for each games. First we need\nto group the data and count records within each group:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-37", "source": [ "yearly_counts <- olympics %>% count(year, season)" ], "cell_type": "code", "execution_count": null, "outputs": [], "metadata": { "attributes": { "classes": [ "> " ], "id": "" } } }, { "id": "cell-38", "source": "

Timelapse data can be visualized as a line plot with years on the x-axis and\ncounts on the y-axis:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-39", "source": [ "ggplot(data = yearly_counts, aes(x = year, y = n)) +\n", " geom_line()" ], "cell_type": "code", "execution_count": null, "outputs": [], "metadata": { "attributes": { "classes": [ "> " ], "id": "" } } }, { "id": "cell-40", "source": "

Unfortunately, this does not work well because our data is quite sparse, datapoints only ever 2 or 4 years.\nLet’s instead use a box plot

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-41", "source": [ "ggplot(data = yearly_counts, aes(x = year, y = n)) +\n", " geom_col()" ], "cell_type": "code", "execution_count": null, "outputs": [], "metadata": { "attributes": { "classes": [ "> " ], "id": "" } } }, { "id": "cell-42", "source": "

We can’t use geom_box() here, instead we should use geom_col() as our data is already aggregated.

\n

We need to tell ggplot to draw a line for each season by modifying\nthe aesthetic function to include group = season:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-43", "source": [ "ggplot(data = yearly_counts, aes(x = year, y = n, group = season)) +\n", " geom_col()" ], "cell_type": "code", "execution_count": null, "outputs": [], "metadata": { "attributes": { "classes": [ "> " ], "id": "" } } }, { "id": "cell-44", "source": "

We will be able to distinguish season in the plot if we add colors (using\ncolor or fill also automatically groups the data:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-45", "source": [ "ggplot(data = yearly_counts, aes(x = year, y = n, fill = season)) +\n", " geom_col()" ], "cell_type": "code", "execution_count": null, "outputs": [], "metadata": { "attributes": { "classes": [ "> " ], "id": "" } } }, { "id": "cell-46", "source": "

If you want the histograms to be side-by-side, we can do that with the “dodge” positioning:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-47", "source": [ "ggplot(data = yearly_counts, aes(x = year, y = n, fill = season)) +\n", " geom_col(position = \"dodge\")" ], "cell_type": "code", "execution_count": null, "outputs": [], "metadata": { "attributes": { "classes": [ "> " ], "id": "" } } }, { "id": "cell-48", "source": "

Integrating the pipe operator with ggplot2

\n

In the previous lesson, we saw how to use the pipe operator %>% to use\ndifferent functions in a sequence and create a coherent workflow.\nWe can also use the pipe operator to pass the data argument to the\nggplot() function. The hard part is to remember that to build your ggplot,\nyou need to use + and not %>%.

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-49", "source": [ "yearly_counts %>%\n", " ggplot(aes(x = year, y = n, fill = season)) +\n", " geom_col()" ], "cell_type": "code", "execution_count": null, "outputs": [], "metadata": { "attributes": { "classes": [ "> " ], "id": "" } } }, { "id": "cell-50", "source": "

The pipe operator can also be used to link data manipulation with consequent data visualization.

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-51", "source": [ "yearly_counts_graph <- olympics %>%\n", " count(year, season) %>%\n", " ggplot(mapping = aes(x = year, y = n, fill = season)) +\n", " geom_col()\n", "\n", "yearly_counts_graph" ], "cell_type": "code", "execution_count": null, "outputs": [], "metadata": { "attributes": { "classes": [ "> " ], "id": "" } } }, { "id": "cell-52", "source": "

Faceting

\n

ggplot has a special technique called faceting that allows the user to split\none plot into multiple plots based on a factor included in the dataset. We will\nuse it to make a time series plot for each season separately:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-53", "source": [ "yearly_counts %>%\n", " ggplot(aes(x = year, y = n, fill = season)) +\n", " geom_col() + facet_wrap(facets=vars(season))" ], "cell_type": "code", "execution_count": null, "outputs": [], "metadata": { "attributes": { "classes": [ "> " ], "id": "" } } }, { "id": "cell-54", "source": "

Now we would like to split the line in each plot by the sex of each individual, sport, and their medal placement.\nTo do that we need to make counts in the data frame grouped by year, season, sport, medal, and noc.

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-55", "source": [ "year_detail_counts <- olympics_small %>%\n", " count(year, season, sport, medal, noc)" ], "cell_type": "code", "execution_count": null, "outputs": [], "metadata": { "attributes": { "classes": [ "> " ], "id": "" } } }, { "id": "cell-56", "source": "

We can now make the faceted plot by splitting further by medal using color\n(within a single plot), and per NOC:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-57", "source": [ "ggplot(data = year_detail_counts, mapping = aes(x = year, y = n, color = medal)) +\n", " geom_line() +\n", " facet_wrap(facets = vars(noc))" ], "cell_type": "code", "execution_count": null, "outputs": [], "metadata": { "attributes": { "classes": [ "> " ], "id": "" } } }, { "id": "cell-58", "source": "

We can also facet both by NOC and sport:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-59", "source": [ "ggplot(data = year_detail_counts, mapping = aes(x = year, y = n, color = medal)) +\n", " geom_line() +\n", " facet_grid(rows = vars(noc), cols = vars(sport))" ], "cell_type": "code", "execution_count": null, "outputs": [], "metadata": { "attributes": { "classes": [ "> " ], "id": "" } } }, { "id": "cell-60", "source": "

You can also organise the panels only by rows (or only by columns):

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-61", "source": [ "# One column, facet by rows\n", "ggplot(data = year_detail_counts, mapping = aes(x = year, y = n, color = medal)) +\n", " geom_line() +\n", " facet_grid(rows = vars(noc))" ], "cell_type": "code", "execution_count": null, "outputs": [], "metadata": { "attributes": { "classes": [ "> " ], "id": "" } } }, { "id": "cell-62", "source": "\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-63", "source": [ "# One row, facet by column\n", "ggplot(data = year_detail_counts, mapping = aes(x = year, y = n, color = medal)) +\n", " geom_line() +\n", " facet_grid(cols = vars(noc))" ], "cell_type": "code", "execution_count": null, "outputs": [], "metadata": { "attributes": { "classes": [ "> " ], "id": "" } } }, { "id": "cell-64", "source": "
\n
\n

ggplot2 before version 3.0.0 used formulas to specify how plots are faceted.\nIf you encounter facet_grid/wrap(...) code containing ~, please read\nhttps://ggplot2.tidyverse.org/news/#tidy-evaluation.

\n
\n

ggplot2 themes

\n

Usually plots with white background look more readable when printed.\nEvery single component of a ggplot graph can be customized using the generic\ntheme() function, as we will see below. However, there are pre-loaded themes\navailable that change the overall appearance of the graph without much effort.

\n

For example, we can change our previous graph to have a simpler white background\nusing the theme_bw() function:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-65", "source": [ "ggplot(data = year_detail_counts, mapping = aes(x = year, y = n, color = medal)) +\n", " geom_line() +\n", " facet_grid(rows = vars(noc), cols = vars(sport)) +\n", " theme_bw()" ], "cell_type": "code", "execution_count": null, "outputs": [], "metadata": { "attributes": { "classes": [ "> " ], "id": "" } } }, { "id": "cell-66", "source": "

In addition to theme_bw(), which changes the plot background to white, ggplot2\ncomes with several other themes which can be useful to quickly change the look\nof your visualization. The complete list of themes is documented in the ggthemes reference. theme_minimal() and\ntheme_light() are popular, and theme_void() can be useful as a starting\npoint to create a new hand-crafted theme.

\n

The\nggthemes package\nprovides a wide variety of options.

\n
\n
Challenge
\n

Use what you just learned to create a plot the relationship between height and weight,\nof participants, broken down by NOC and Sport.

\n
👁 View solution\n
\n
ggplot(data = olympics_small, mapping = aes(x = height, y = weight, color = medal)) +\n    geom_point() +\n    facet_grid(rows = vars(noc), cols = vars(sport))\n
\n
\n
\n

Customization

\n

Take a look at the ggplot2 cheat sheet, and\nthink of ways you could improve the plot.

\n

Now, let’s change names of axes to something more informative than ‘year’\nand ‘n’ and add a title to the figure:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-67", "source": [ "ggplot(data = year_detail_counts, mapping = aes(x = year, y = n, fill = medal)) +\n", " geom_col() +\n", " facet_grid(rows = vars(noc), cols = vars(sport)) +\n", " labs(title = \"Participants and medals over the years\",\n", " x = \"Year\",\n", " y = \"Number of individuals\") +\n", " theme_bw()" ], "cell_type": "code", "execution_count": null, "outputs": [], "metadata": { "attributes": { "classes": [ "> " ], "id": "" } } }, { "id": "cell-68", "source": "

The axes have more informative names, but their readability can be improved by\nincreasing the font size. This can be done with the generic theme() function:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-69", "source": [ "ggplot(data = year_detail_counts, mapping = aes(x = year, y = n, fill = medal)) +\n", " geom_col() +\n", " facet_grid(rows = vars(noc), cols = vars(sport)) +\n", " labs(title = \"Participants and medals over the years\",\n", " x = \"Year\",\n", " y = \"Number of individuals\") +\n", " theme_bw()\n", " theme(text=element_text(size = 16))" ], "cell_type": "code", "execution_count": null, "outputs": [], "metadata": { "attributes": { "classes": [ "> " ], "id": "" } } }, { "id": "cell-70", "source": "

Note that it is also possible to change the fonts of your plots. If you are on\nWindows, you may have to install\nthe extrafont package, and follow the\ninstructions included in the README for this package.

\n

After our manipulations, you may notice that the values on the x-axis are still\nnot properly readable. Let’s change the orientation of the labels and adjust\nthem vertically and horizontally so they don’t overlap. You can use a 90 degree\nangle, or experiment to find the appropriate angle for diagonally oriented\nlabels. We can also modify the facet label text (strip.text) to italicize the genus\nnames:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-71", "source": [ "ggplot(data = year_detail_counts, mapping = aes(x = year, y = n, fill = medal)) +\n", " geom_col() +\n", " facet_grid(rows = vars(noc), cols = vars(sport)) +\n", " labs(title = \"Participants and medals over the years\",\n", " x = \"Year\",\n", " y = \"Number of individuals\") +\n", " theme_bw()\n", " theme(axis.text.x = element_text(colour = \"grey20\", size = 12, angle = 90, hjust = 0.5, vjust = 0.5),\n", " axis.text.y = element_text(colour = \"grey20\", size = 12),\n", " strip.text = element_text(face = \"italic\"),\n", " text = element_text(size = 16))" ], "cell_type": "code", "execution_count": null, "outputs": [], "metadata": { "attributes": { "classes": [ "> " ], "id": "" } } }, { "id": "cell-72", "source": "

If you like the changes you created better than the default theme, you can save\nthem as an object to be able to easily apply them to other plots you may create:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-73", "source": [ "grey_theme <- theme(axis.text.x = element_text(colour=\"grey20\", size = 12,\n", " angle = 90, hjust = 0.5,\n", " vjust = 0.5),\n", " axis.text.y = element_text(colour = \"grey20\", size = 12),\n", " text=element_text(size = 16))\n", "\n", "ggplot(data = year_detail_counts, mapping = aes(x = year, y = n, fill = medal)) +\n", " geom_col() +\n", " facet_grid(rows = vars(noc), cols = vars(sport)) +\n", " grey_theme" ], "cell_type": "code", "execution_count": null, "outputs": [], "metadata": { "attributes": { "classes": [ "> " ], "id": "" } } }, { "id": "cell-74", "source": "
\n
Challenge
\n

With all of this information in hand, please take another five minutes to either\nimprove one of the plots generated in this exercise or create a beautiful graph\nof your own. Use the RStudio ggplot2 cheat sheet\nfor inspiration.

\n

Here are some ideas:

\n
    \n
  • See if you can change the plot type to another plot
  • \n
  • Can you find a way to change the name of the legend? What about its labels?
  • \n
  • Try using a different color palette (see https://r-graphics.org/chapter-colors).
  • \n
\n
👁 View solution\n
\n

This optional exercise currently lacks solutions. If you have them, please feel free to contribute suggestions here :)

\n
\n
\n

Arranging plots

\n

Faceting is a great tool for splitting one plot into multiple plots, but\nsometimes you may want to produce a single figure that contains multiple plots\nusing different variables or even different data frames. The patchwork\npackage allows us to combine separate ggplots into a single figure while keeping\neverything aligned properly. Like most R packages, we can install patchwork\nfrom CRAN, the R package repository, if it isn’t already available:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-75", "source": [ "# install.packages(\"patchwork\")" ], "cell_type": "code", "execution_count": null, "outputs": [], "metadata": { "attributes": { "classes": [ "> " ], "id": "" } } }, { "id": "cell-76", "source": "

After you have loaded the patchwork package you can use + to place plots\nnext to each other, / to arrange them vertically, and plot_layout() to\ndetermine how much space each plot uses:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-77", "source": [ "library(patchwork)\n", "\n", "plot_weight <- olympics_small %>% ggplot(aes(x=noc, y=weight)) +\n", " geom_boxplot() +\n", " labs(x = \"NOC\", y = expression(log[10](Weight))) +\n", " scale_y_log10()\n", "\n", "plot_height <- olympics_small %>% ggplot(aes(x=noc, y=height)) +\n", " geom_boxplot() +\n", " labs(x = \"NOC\", y = expression(log[10](Height))) +\n", " scale_y_log10()\n", "\n", "plot_weight / plot_height + plot_layout(heights = c(3, 2))" ], "cell_type": "code", "execution_count": null, "outputs": [], "metadata": { "attributes": { "classes": [ "> " ], "id": "" } } }, { "id": "cell-78", "source": "

You can also use parentheses () to create more complex layouts. There are\nmany useful examples on the patchwork website

\n

Exporting plots

\n

After creating your plot, you can save it to a file in your favorite format. The\nExport tab in the Plot pane in RStudio will save your plots at low\nresolution, which will not be accepted by many journals and will not scale well\nfor posters. The ggplot2 extensions website provides a list\nof packages that extend the capabilities of ggplot2, including additional\nthemes.

\n

Instead, use the ggsave() function, which allows you to easily change the\ndimension and resolution of your plot by adjusting the appropriate arguments\n(width, height and dpi):

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-79", "source": [ "my_plot <- year_detail_counts %>% ggplot(aes(x = year, y = n, fill = medal)) +\n", " geom_col() +\n", " facet_grid(rows = vars(noc), cols = vars(sport)) +\n", " labs(title = \"Participants and medals over the years\",\n", " x = \"Year\",\n", " y = \"Number of individuals\") +\n", " theme_bw()\n", " theme(axis.text.x = element_text(colour = \"grey20\", size = 12, angle = 90, hjust = 0.5, vjust = 0.5),\n", " axis.text.y = element_text(colour = \"grey20\", size = 12),\n", " strip.text = element_text(face = \"italic\"),\n", " text = element_text(size = 16))\n", "\n", "ggsave(\"name_of_file.png\", my_plot, width = 15, height = 10)\n", "\n", "## This also works for plots combined with patchwork\n", "plot_combined <- plot_weight / plot_height + plot_layout(heights = c(3, 2))\n", "ggsave(\"plot_combined.png\", plot_combined, width = 10, dpi = 300)" ], "cell_type": "code", "execution_count": null, "outputs": [], "metadata": { "attributes": { "classes": [ "> " ], "id": "" } } }, { "id": "cell-80", "source": "

Note: The parameters width and height also determine the font size in the\nsaved plot.

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-81", "source": [ "### Final plotting challenge:\n", "## With all of this information in hand, please take another five\n", "## minutes to either improve one of the plots generated in this\n", "## exercise or create a beautiful graph of your own. Use the RStudio\n", "## ggplot2 cheat sheet for inspiration:\n", "## https://posit.co/wp-content/uploads/2022/10/data-visualization-1.pdf" ], "cell_type": "code", "execution_count": null, "outputs": [], "metadata": { "attributes": { "classes": [ "> " ], "id": "" } } }, { "id": "cell-82", "source": "\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "cell_type": "markdown", "id": "final-ending-cell", "metadata": { "editable": false, "collapsed": false }, "source": [ "# Key Points\n\n", "- Plotting is easy with ggplot2.\n", "- Start small, and build up plots over time.\n", "\n# Congratulations on successfully completing this tutorial!\n\n", "Please [fill out the feedback on the GTN website](https://training.galaxyproject.org/training-material/topics/data-science/tutorials/data-manipulation-olympics-viz-r/tutorial.html#feedback) and check there for further resources!\n" ] } ], "etadata": { "kernelspec": { "display_name": "R", "language": "R", "name": "r" }, "language_info": { "codemirror_mode": "r", "file_extension": ".r", "mimetype": "text/x-r-source", "name": "R", "pygments_lexer": "r", "version": "4.1.0" } } }