Session 6 ggplot2 in Action (part 1)

6.1 Recap & Workshop

In this session we will be looking at each others code and data visualisations. The goal is to learn to read code with understanding. Sharing our code is also a good way for us to learn to write code that is human-readable. Applying consistent style to your code is a good habit to get into, but like all things in R there are also packages that can help you.

The styler package is a great tool to use when we want to format our code in a consistent fashion. There is also a styler add-in for RStudio which can be accessed from the top toolbar under Addins.

The other package that is incredibly useful is the janitor package. There are many great functions in the package, so I suggest you read the documentation but the one that I use the most freqently is clean_names.

library(janitor)
# Apply clean_names to your imported tibble
my_data <- read_*(...) %>% 
  clean_names()

6.2 Participant Submissions

In order for us to really focus on learning to read code, I am going to present each code submission without the subsequent data visualisation. All the way back in Session 2 we did the exercise of trying to describe our favourite species without a picture. This is the ggplot2 version of that.

Together, let us try to construct a mental image of the plot from the code we are reading. Feel free to use a pen and notepad as we do this.

6.2.1 Brishan

# install.packages("palmerpenguins")
library(palmerpenguins)
data(penguins)

library(tidyverse)
library(lubridate)

# I used penguins_raw because of the change in variable types that penguins has
penguins_raw %>%
#renaming relevant variables so the names makes sense and with underscores not spaces
  rename(
    bill_length_mm = `Culmen Length (mm)`,
    bill_depth_mm = `Culmen Depth (mm)`,
    mass_g = `Body Mass (g)`,
    flipper_lenght_mm = `Flipper Length (mm)`
  ) %>%
# get year alone
  mutate(
    year = year(`Date Egg`)
  ) %>% 
# choosing the variables that I am interested in  
  select(
    Species,
    Island,
    Stage,
    year,
    bill_length_mm,
    bill_depth_mm,
    flipper_lenght_mm, # GM: Small typo here (but var is not used in plot)
    mass_g,
    Sex
  ) %>%
#making the plot of bill length versus depth 
  ggplot(
    aes(
      x = bill_length_mm,
      y = bill_depth_mm,
      color = Species,# coloring each point by species
      shape = Island, # making the shapes specific to the islands samples were collected
    )
  ) + geom_point(na.rm = TRUE) + # using a scatter plot
  facet_grid( rows = vars(year)) + # creating three plots per year of sampling
#adding relevant labs to plot
  labs(
    title = "Penguins species bill distribution",
    subtitle = "Bill length versus bill depth comparing species found on three islands",
    x = "Depth (mm)", 
    y = "Length (mm)",
    fill = "Type"
  ) +
# generating theme of graph
  theme(
    plot.title = element_text(colour = "#000000", size = 14, face = "bold"),
    plot.subtitle = element_text(colour = "#001eff"),
    axis.title.x = element_text(face = "bold", size = 11, colour = "#000000"),
    axis.text.x = element_text(face = "bold", size = 11, colour = "#000000"),
    axis.title.y = element_text(size = 11, face = "bold", colour = "#000000"),
    axis.text.y = element_text(face = "bold", size = 11, colour = "#000000"),
    legend.position = "right",
    panel.grid.minor.x = element_blank(), # Reduce the clutter on the background panel
    panel.grid.minor.y = element_blank(),
    strip.text = element_text(colour = "white", face = "bold", size = 11),
    strip.background = element_rect(fill = "#001eff"),
  )

6.2.2 Lynn

summary_wt <- tp02_2 %>%
  group_by(family_id, host, fo_host) %>%
  summarise(
    mean_wt = mean(tp_weight),
    mean_frt = mean(tp_fruits)
      ) %>% 
  ggplot(
      aes(
        x = host,
        y = mean_wt,
        colour = fo_host #I also tried colour = family_id
      )
      ) +
  geom_line() + 
  theme_classic() +
  labs(
    title = "Parasitic plant performance on two hosts",
    x = "Host",
    y = "Parasite weight (g)"
  ) 

summary_wt #Not what I want!!

6.2.3 Kim

# install.packages("palmerpenguins")
library(palmerpenguins)
data(penguins)

## Are there species and island differences in flipper allometry?
penguins %>%
ggplot (
data = penguins,
mapping = aes (
x = body_mass_g,
y = flipper_length_mm,
colour =  species,
shape = island
)
)+     geom_point() 

## Are there species and island differences in beak allometry?
penguins %>%
ggplot (
data = penguins,
mapping = aes (
x = body_mass_g,
y = bill_depth_mm,
colour =  species,
shape = island
)
)+     geom_point() 


### I tried to put labels on, couldn’t get it to work 
# Fig1 <- Fig1 +
# labs( 
# title = “Penguin Body Mass:Flipper Allometry”, 
# x = “Body “Mass (g)”, 
# y = “Flipper Length (mm)” ,
# caption = “Data sampled 2007-2009, Palmer Peninsula Antarctica”
# )

6.2.4 Laura

library(tidyverse)
library(here)
library(ggplot2)
bouts<- read_delim("Data/Bouts por hora.csv", 
                         ";", escape_double = FALSE, trim_ws = TRUE)


##both on and off bouts
#Make bout a factor with levels in the order we want them
bouts$Bout = factor(bouts$Bout, levels=c("ON", "OFF"))

#create the plot
bouts %>%   
  ggplot(
    aes(
      x=Hour, y= Minutes, color=Bout
      )
  )+ 
  
  #add geom as boxplot
  geom_boxplot()+
  
  #add labels for title, subtitle and axis
  labs(
    title=expression(paste("Incubation behavior of ",italic("Megascops albogularis"), " per hour")),
    subtitle="Green indicates time on the nest and red indicates time off the nest",
       x="Hour of the day", 
       y="Time (min)"
  )+
  
  #add the hours of the day we want as scale, as well as the labels we want on them
  scale_x_discrete(
    limits=c("18","19","20","21","22","23","24","1","2","3","4","5"
             ),
    labels=c("18:00","19:00","20:00","21:00","22:00","23:00","24:00","1:00","2:00","3:00","4:00","5:00")
    )+
  
  #Add the colors of the bout categories
  scale_color_manual(
    values=c("#baeb34", "#d42020"))+
  
  #Create a faced grid
      facet_grid(rows=vars(Bout))+
  
  #add theme features
  theme(
    plot.title = element_text(color = "#1b2533"),
    plot.subtitle = element_text(color="#324157"),
    strip.background = element_rect(fill = "#1b2533"),
    strip.text = element_text(colour = c("white"), face = "bold", size = 11),
    panel.background = element_rect(color="#546d91"),
legend.position ="none",
axis.text.x = element_text(angle=45, size=9, vjust=0.5),
axis.title = element_text(color="#324157"))

#Doubts:
##How do I change the color of each facet grid title?
##Is there a way of changing each facet grid scale?