Tutorial Aims

Introduction

This tutorial will guide you through some extra ways to visualise data… And even better… We get to use a Disney data set! So if you’re a Disney adult this code will add a bit of spice to your learning… if not… well that’s a shame (you should probably go watch the Lion King to change your mind). We all need to to release our inner child once in a while.

Without effect data visualisation it almost pointless. There are so many different options for different types of data so it is important to know all the possible options to optimise communication of data to the reader.

This data set takes reviews of … popular Disney films over the last few decades. Firstly lets read in the data and view the first few lines to see what we are dealing with…

Data Manipulation

### LIBRARIES ###
library(tidyverse) # contains ggplot and dplyr

setwd("C:/Users/tyler/Documents/Ecological and Environmental Science With Management/Year 3/tutorial-taday2002")

### LOAD IN DATA SET WITH DIRECTORY ###
disney <- read.csv("Raw_Materials/Data_Disney.csv") # This works within an R project
# If you aren't, you will need to set a file working directory in the format setwd(/File_path/data_name.csv) - as shown above this code. 
# You can find the file path within your file explorer on the drop down menu above your file location. 
# Copy and paste this into setwd() and remember to flip the "\" to "/".

# Lets look at our data set
head(disney)
##   film_name film_year        author_name review_date score   POU
## 1 Peter pan      1953       SpencerDeane   26-Jun-18     9  0.00
## 2 Peter pan      1953       AdrianaAdams   20-May-15    10 33.33
## 3 Peter pan      1953      lukeduke20164   10-Oct-18     8  0.00
## 4 Peter pan      1953 witch-nikki-porras   14-Jul-13     0 11.11
## 5 Peter pan      1953      sarah-tranter   27-Dec-04     7 40.00
## 6 Peter pan      1953   julia-ff-solheim   13-Aug-11     0 16.67

Here we can see the columns within the data set. We can see there is film name, with adjacent year released, review date, reviewer name, film rating/score and usefulness index (we won’t be using this) Running the first few rows is good practice when first looking at your data.

If we just explore the data set, we can see that a lot of the code is actually in a different language. But no bother, it is only a few, so we cam change it manually.

# Look at the Disney film names - see some are in French
unique(disney$film_name)
##  [1] "Peter pan"                             
##  [2] "Alice nel paese delle meraviglie"      
##  [3] "Cenerentola"                           
##  [4] "La Spada nella Roccia"                 
##  [5] "The Jungle Book"                       
##  [6] "Mary Poppins"                          
##  [7] "The Aristocats"                        
##  [8] "The Rescuers"                          
##  [9] "The Many Adventures of Winnie the Pooh"
## [10] "The Little Mermaid"                    
## [11] "Tron"                                  
## [12] "Oliver & Company"                      
## [13] "Aladdin"                               
## [14] "The Lion King"                         
## [15] "Hercules"                              
## [16] "The Emperor's New Groove"              
## [17] "Spirited Away"                         
## [18] "Lilo & Stitch"                         
## [19] "Tangled"                               
## [20] "Brave"                                 
## [21] "Frozen"
# Change Disney french names to their English names for readability
disney <- disney %>%
  mutate(film_name = case_when(film_name=="Cenerentola" ~ "Cinderella",
                               film_name!="Cenerentola" ~ film_name)) %>%
  mutate(film_name = case_when(film_name=="La Spada nella Roccia" ~ "The Sword in the Stone",
                               film_name!="La Spada nella Roccia" ~ film_name)) %>%
  mutate(film_name = case_when(film_name=="Alice nel paese delle meraviglie" ~ "Alice in Wonderland",
                               film_name!="Alice nel paese delle meraviglie" ~ film_name))

This permanently alters the variable names in the column. We use piping (%>%) here to make the code more efficient and readable. By naming this pipe Disney, it means it overwrites what is in the columns. Now if we run the names in film_name, this is what we see:

unique(disney$film_name)
##  [1] "Peter pan"                             
##  [2] "Alice in Wonderland"                   
##  [3] "Cinderella"                            
##  [4] "The Sword in the Stone"                
##  [5] "The Jungle Book"                       
##  [6] "Mary Poppins"                          
##  [7] "The Aristocats"                        
##  [8] "The Rescuers"                          
##  [9] "The Many Adventures of Winnie the Pooh"
## [10] "The Little Mermaid"                    
## [11] "Tron"                                  
## [12] "Oliver & Company"                      
## [13] "Aladdin"                               
## [14] "The Lion King"                         
## [15] "Hercules"                              
## [16] "The Emperor's New Groove"              
## [17] "Spirited Away"                         
## [18] "Lilo & Stitch"                         
## [19] "Tangled"                               
## [20] "Brave"                                 
## [21] "Frozen"

Yey! It’s all in the right language!

1. Pie charts

Okay, the first graph we are going to make is a pie chart of the number of reviews per film.

#Here counts how many reviews were given per Disney film
review_numbers <- disney %>%
  count(film_name)

This creates a new object called review_numbers. It pipes through all the different Disney films and counts how many records of each film have been submitted.

# Create pie chart
slices <- c(review_numbers$n) #n is the calculated number of reviews - here it tells R that these will be the slices
lbls <- c(review_numbers$film_name) # this adds the labels of film name to the chart
pct <- round(slices/sum(slices)*100) # this adds the percentages next to the labels
lbls <- paste(lbls, pct) #it pastes film names in lbls with their corresponding percentages from pct together
lbls <- paste(lbls,"%",sep="") # ad % to labels

Okay, perfect. Simple. We have told R what it needs. Now lets plot the pie chart. Here we tell it the slices, the labels and colour of the pie chart sections and give it an appropriate title. Generally, in scientific figures we don’t include titles, but here it is necessary for the fugure to be fully informative.

pie(slices,labels = lbls, col=rainbow(length(lbls)), cex = 0.7, #cex = specifies label text size. 
    main="Proportion of reviews per Disney film ")


“Practically perfect in every way” – Mary Poppins


2. Split Histogram

Okay now we are going to make a split histogram of the distribution of scores between two time decades: 2000-2010, and 2011-2021. This will be set-up in the format of a population pyramid which is commonly found in ecological population studies. We are going to do this for one film within the data set. You can select any film of your choosing for this, just be sure to be consistent with name changing. So firstly we want to create a new data set of just the Lion King by filtering it out of ‘disney’.

Lion_king_data <- disney %>% # This creates a new data set called Lion_king_data. 
  filter(film_name == "The Lion King") %>% # We pipe through filter out only the rows referencing the Lion King.
  mutate(review_date = as.Date(review_date, format = "%d-%b-%y")) # This tell R that the column review_date is a date and the format it follows. 

Okay. Perfect. Lets keep going.

“Giving up is for rookies” – Hercules

# Filter data for the specified time ranges
reviews_2000_2010 <- dplyr::filter(Lion_king_data, lubridate::year(review_date) %in% 2000:2010)
reviews_2011_2021 <- dplyr::filter(Lion_king_data, lubridate::year(review_date) %in% 2011:2021)

Here we create two separate data sets of the two decades. Then we create a new function in R to count the frequency of scores, as shown below:

# Function to calculate frequency of each score from 1 to 10
calculate_score_frequency <- function(data) {
  freq <- table(data$score) # creates a frequency table of the score column and how many times each value is present. 
  freq <- as.data.frame(freq) # Turns freq into a data frame. 
  names(freq) <- c("Score", "Frequency") # renames column of the new data frame
  freq # This returns the modified data frame 
}

Now we can use this function on the reviews_2000_2010 and reviews_2000_2010 data frames we just filtered.

#### Calculate frequency of each score for both time ranges
freq_2000_2010 <- calculate_score_frequency(reviews_2000_2010)
freq_2011_2021 <- calculate_score_frequency(reviews_2011_2021)

# Merge the frequency data
merged_freq <- merge(freq_2000_2010, freq_2011_2021, by = "Score", all = TRUE) # Then we merge the two objects into one data set by score. 
merged_freq[is.na(merged_freq)] <- 0  # Replace NA with 0 for missing scores

Okay. now we have the correctly formatted and calculated score frequencies that can we can plot. Remember, we create population pyramids to display distributions of various age groups and genders within a point in time. Here, we are making a similar thing with the same format, but just more for us Disney nerds.

Now lets plot our graph!

# Plotting the histogram
(ggplot(merged_freq, aes(x = Score)) + # Plot final, extracted and manipulated data set. 
  geom_bar(aes(y = Frequency.x, fill = "Years 2000-2010"), stat =  "identity", alpha = 0.7, position = "dodge") +
  geom_bar(aes(y = -Frequency.y, fill = "Years 2011-2021"), stat = "identity", alpha = 0.7, position = "dodge") +
  labs(title = "Frequency of Scores for The Lion King", x = "Score", y = "Frequency") + # Labels the x and y axis
  scale_y_continuous(labels = abs) + # tells it that the 'negative' y values to be plotted as positive. 
  coord_flip() + # flips orientation of the x and y axis
  theme_minimal() + # Sets graph with a minimalist style, but you can change this to whatever you prefer
  scale_fill_manual(name = "Time Period",
                    values = c("Years 2000-2010" = "skyblue", "Years 2011-2021" = "salmon"), # goves the plots different colours depending on the time period it is in. 
                    labels = c("Years 2000-2010", "Years 2011-2021")) +
  theme(legend.position = "bottom")) # puts the legend at the bottom - you can change to right, left or top easily. 


We have used the function geom_bar() twice which plots the bars of the separate time periods on two separate plots. If you were doing a regular population pyramid, you could use this base code to create it.

All is well… no need to stress.


3. Stacked Barplot

The last graph we are going to make is a stacked barplot. This is quite straight forward. What we want to do is have all the films on the x axis with bar plot of review frequency on the y axis. Then We want to show the frequency of different score for each film using stacks. Lets start off simple.
We don’t need to do much data manipulation with columns, we just need the original data.

(plot <- ggplot(disney, aes(x = film_name, fill = as.factor(score))) + # set score as factor to treat these more like categories than continuous numerical values. 
  geom_bar() + # add bars along x-axis 
  labs(title = "Stacked Bar Plot of Score Distributions for Disney Films",
       x = "Film Name", y = "Frequency") +
  theme_minimal() + # sets theme
  theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust = 1), # makes the angle of the x axis at an angle so it is more readible 
        axis.text.y = element_text(angle = 45, vjust = 1, hjust = 1)))


While this graph looks great, the colours are quite intense and don’t visually tell us much without having to really study the graph. To fix this, we can specify the colours that correlate to high and low scores. For example we can so a sliding scale from red to green.

Run this code below:

my_colors <- colorRampPalette(c("red", "orange", "green"))(11) # This creates a gradient of colours from red to orange to green and puts it into 1 object whihc we can call later.

(plot <- ggplot(disney, aes(x = film_name, fill = as.factor(score))) +
  geom_bar() +
  labs(title = "Stacked Bar Plot of Score Distributions for Disney Films",
       x = "Film Name", y = "Frequency") +
  scale_fill_manual(name = "Score", values = setNames(my_colors, levels(disney$score))) + # here we have called the colours and specified the levels being the scores 1-10
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust = 1),
        axis.text.y = element_text(angle = 45, vjust = 1, hjust = 1)))

  Now we can easily see the distribution of scores as well as the number of reviews given per film. This graph more so combines the information presented in the pie chart and split histogram we did earlier in the tutorial. This graph is visually much more informative and includes a summary of all of the data.

Coding can be hard. It can be so unbelievably frustrating when you are drowning in error messages. But keep going, keep researching, keep trying…

“From failure we learn, from success not so much” – Meet the Robinsons