Tutorial-05

Author

Your name

Data Wrangling for Visualisation in R

Keep the data folder in the same folder as this file. Set your working directory using Session > Set Working Directory > To Source File Location.

Replace each ??? with your own code. Then change eval: false to eval: true in that chunk so it runs when you render.

Setup

library(tidyverse)

Exercise 1: Human powered

The file swiss_exports.csv contains monthly export data for Switzerland. Each row is a month. There is a Date column, a Year column, and one column for each destination country, named using a two letter country code.

Your goal is to compare total exports to each country in 1988 and 2018.

Question 1.1: Read in the data

Run this code to read in the data. Notice that col_types specifies the type of each column.

swiss_wide <- read_csv(
  "data/swiss_exports.csv",
  col_types = cols(
    Date = col_date(format = "%Y-%m-%d"),
    Year = col_integer(),
    .default = col_double()
  )
)

Question 1.2: Make the data long

Look at your data in the console using glimpse() or View(), and check the column names.

glimpse(swiss_wide)
View(swiss_wide)

Notice there is no country or exports column, so we need to make them. Use pivot_longer() to create a column of country codes called country and a column of values called exports. Hint: it is easier to say which columns you do not want to pivot.

swiss_long <- swiss_wide |> 
  pivot_longer(
    cols = -c(???, ???), 
    names_to = "???", 
    values_to = "???"
  )

Question 1.3: Yearly totals

Use group_by() and summarise() to find the total exports to each country in each year. Why is this easier with long data?

swiss_yearly <- swiss_long |> 
  group_by(???, ???) |> 
  summarise(total_exports = ???(???), .groups = "drop")

[Insert your answer here]

Question 1.4: Reshape for the plot

We want to plot 1988 exports on the x-axis and 2018 exports on the y-axis. Keep only those two years, then use pivot_wider() so that each year has its own column.

swiss_compare <- swiss_yearly |> 
  filter(Year %in% c(???, ???)) |> 
  pivot_wider(names_from = ???, values_from = ???)

Question 1.5: Remove zeros

We can’t show zero on a log scale. Keep only the countries with exports greater than zero in both years. Hint: a variable name that is a number needs backticks, for example `1988`.

swiss_nonzero <- swiss_compare |> 
  filter(??? > 0, ??? > 0)

Question 1.6: Plot the result

Run the code below to plot the data without a log transform.

ggplot(data = swiss_nonzero) + 
  geom_point(aes(x = `1988`, y = `2018`), alpha = 0.6) + 
  theme_bw() + 
  labs(title = "Swiss exports by destination country",
       x = "Total exports in 1988",
       y = "Total exports in 2018")

Now run it again with a log transform on both axes.

ggplot(data = swiss_nonzero) + 
  geom_point(aes(x = `1988`, y = `2018`), alpha = 0.6) + 
  scale_x_log10() + 
  scale_y_log10() + 
  theme_bw() + 
  labs(title = "Swiss exports by destination country",
       x = "Total exports in 1988 (log scale)",
       y = "Total exports in 2018 (log scale)")

Compare the two plots. Why is the log transform important here? What can you see in the second plot that was hidden in the first?

[Insert your answer here]

Why did we need a separate column for each year to make these plots?

[Insert your answer here]

Exercise 2: AI powered

In Exercise 1 you compared two years. Now you will look at the top five export destinations, based on total exports in 2018, and how exports to each of them changed from 1988 to 2018.

Your goal is to reproduce the plot below from swiss_exports.csv.

See the tutorial sheet for the target plot.

Question 2.1: Read the plot

Before writing any code or prompts, describe the plot using the grammar of graphics. We will look at the data layer in Question 2.2.

Component My description
Aesthetic mappings ???
Geometry ???
Scales ???
Labels ???
Theme ???

Question 2.2: Get the data layer right

The data layer comes first in the grammar of graphics: your data needs to be in the right shape before you can create the plot. Look at the data below. How is it different from the data the plot needs?

swiss_exports <- read_csv("data/swiss_exports.csv")
glimpse(swiss_exports[, 1:8])
Rows: 372
Columns: 8
$ Date <date> 1988-01-01, 1988-02-01, 1988-03-01, 1988-04-01, 1988-05-01, 1988…
$ Year <dbl> 1988, 1988, 1988, 1988, 1988, 1988, 1988, 1988, 1988, 1988, 1988,…
$ AD   <dbl> 167909, 470360, 369814, 198309, 418874, 689409, 468278, 735697, 6…
$ AE   <dbl> 13478266, 26128749, 20755283, 17547923, 15881333, 20056980, 19557…
$ AF   <dbl> 416619, 216036, 35456, 613661, 278839, 354718, 508456, 303784, 20…
$ AG   <dbl> 2083, 43935, 11437, 9143, 812324, 10284, 24878, 11297, 41043, 755…
$ AI   <dbl> 0, 0, 2497, 2100, 7511, 1715, 3601, 739, 60378, 538, 3688, 0, 423…
$ AL   <dbl> 95239, 216642, 172260, 505233, 1031885, 130558, 600288, 347447, 2…
What to look for Data I have Data the plot needs
What is one row? ??? ???
Where are the countries? ??? ???
Which countries? ??? ???
What time period is each export value? ??? ???

[Insert your answer here]

Question 2.3: Prompt AI to wrangle

Attach swiss_exports.csv to your AI tool. Complete the scaffold below to describe the data you need. Use your answer to Question 2.2.

I am a beginner learning data wrangling in R.
I have attached swiss_exports.csv, which is saved in a folder
called data.
Can you write some code in R to help me wrangle my data so that I
have ... [ADD WHAT YOU NEED HERE] ...
Please use the tidyverse and explain each line of code.
Save the new data into a variable called trend_data, I'm going to
use that for plotting shortly.

Run the code and check that trend_data is the data you described. Don’t assume it is correct.

# [Insert your answer here]

Question 2.4: Prompt AI to plot

Complete the scaffold below to create the plot. Use your grammar of graphics description from Question 2.1.

I am a beginner learning to plot in R with ggplot2.
I have a data frame called trend_data that I want to plot.
Can you write some code in R to help me make a plot that has ...
[ADD YOUR GRAMMAR OF GRAPHICS DESCRIPTION HERE] ...
Please explain each line of code.
# [Insert your answer here]

Question 2.5: Compare and reflect

Compare your plot with the target.

  • What is different? Fix it by editing the code or improving your prompt.
  • What did you have to correct?
  • What did the AI assume that you didn’t tell it?
  • Can you explain what each line of code does?

[Insert your answer here]

Question 2.6: Colour blind friendly colours

Prompt AI to make your plot colour blind friendly.

Can you change my plot so that ... [ADD WHAT YOU NEED HERE] ...
# [Insert your answer here]

In Your Own Time

Tidy data and first normal form

Often you need to tidy your data before you can start wrangling or plotting. A table is in first normal form when each cell holds a single value, and there are no repeating groups of columns. Tidy data goes further: each variable is a column, each observation is a row, and each value is a cell.

Which of these databases satisfies first normal form? Why?

Database A:

# A tibble: 3 × 2
  name        social_media                   
  <chr>       <chr>                          
1 Jane Smith  Facebook: jsChampion           
2 Kamal Usman Twitter: kusman, LinkedIn: ku87
3 Li Xiao     WeChat: lx99                   

Database B:

# A tibble: 4 × 2
  name        social_media        
  <chr>       <chr>               
1 Jane Smith  Facebook: jsChampion
2 Kamal Usman Twitter: kusman     
3 Kamal Usman LinkedIn: ku87      
4 Li Xiao     WeChat: lx99        

[Insert your answer here]

More wrangling practice

Using swiss_long, practise mutate(), filter(), select() and arrange(): create a month column, then find the top five export destinations in December 2018.

# [Insert your answer here]