Lesson Overview: Crafting Your Data Storybook

Welcome to our storytelling session, where data comes alive on the pages of ggplot2! Today, you'll develop the ability to weave multiple data narratives together onto a single canvas. This process is much akin to assembling a scrapbook, where each photo or plot, in this case, adds depth to the story. By the end of this lesson, you'll be able to create a multi-plot narrative by using layers on the same axis and within a single figure using R syntax.

Understanding Subplots and Axes

Imagine you're building a scrapbook. Each page can hold multiple pictures, and you have the freedom to decide where each photo goes. Subplots function similarly, assisting us in positioning multiple charts within a plot grid. We'll learn how to organize our data tales neatly on a page using subplots in R, specifically a R package called cowplot.

Here's a detailed example of creating subplots:

# install and load necessary libraries
install.packages("cowplot")
library(ggplot2)
library(cowplot)

# Create some data
df1 <- data.frame(x = c(1, 2, 3), y = c(2, 3, 4))
df2 <- data.frame(x = c(1, 2, 3), y = c(1, 3, 3))

# Define two line plots
p1 <- ggplot(df1, aes(x = x, y = y)) +
      geom_line(colour = "blue") +
      ggtitle("Plot 1")
p2 <- ggplot(df2, aes(x = x, y = y)) +
      geom_line(colour = "red") +
      ggtitle("Plot 2")

# Arrange the plots with grid arrange
plot <- plot_grid(p1, p2, ncol = 2)

plot_grid organizes the plots within a grid. By setting ncol = 2, we arrange plots like photos on a scrapbook page, telling parts of the larger story side by side.

Plotting Students' Performance

Let's consider a more meaningful dataset. Imagine we have the data for two students' average marks and we want to compare their performance using plots:

first_student_marks <- c(3.8, 3.9, 3.8, 4.1, 4.4, 4.2, 4.5, 4.5, 4.7)
second_student_marks <- c(4, 3.9, 4.1, 4.1, 4.1, 3.9, 3.8, 3.7, 3.5)
semesters <- c(1, 2, 3, 4, 5, 6, 7, 8, 9)

Here's how we plot these graphs:

studentA <- data.frame(semester = semesters, marks = first_student_marks)
studentB <- data.frame(semester = semesters, marks = second_student_marks)

p1 <- ggplot(studentA, aes(x = semester, y = marks)) +
      geom_line() +
      ylim(c(3, 5)) +
      ggtitle("Student A")
p2 <- ggplot(studentB, aes(x = semester, y = marks)) +
      geom_line() +
      ylim(c(3, 5)) +
      ggtitle("Student B")

plot <- plot_grid(p1, p2, ncol = 2)

By using a common y-axis limit with ylim, we make the comparison more apparent.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal