Lesson 5
Grouping Data Narratives: Mastering Subplots and Figures in Matplotlib
Lesson Overview: Crafting Your Data Storybook

Welcome to our storytelling session, where data comes alive on the pages of Matplotlib! Today, you'll become adept at weaving multiple data narratives together on a single canvas. This process is much like assembling a scrapbook, where every photo, or in this case, plot, adds depth to the story. By the end of this lesson, you'll know how to create a multi-plot narrative using layers on the same axis and within a single figure.

Understanding Subplots and Axes

Imagine you're building a scrapbook. Each page can hold multiple pictures, and you can decide where each photo goes. Subplots work similarly, helping us position multiple charts within a plot grid. We'll learn how to organize our data tales neatly on a page using subplots.

Here's a detailed example of creating subplots:

Python
1import matplotlib.pyplot as plt 2import numpy as np 3 4plt.figure() # Start a new figure, your scrapbook page. 5 6x1 = np.array([0, 1, 2]) 7y1 = np.array([0, 1, 4]) 8# Begin a subplot grid: 1 row and 2 columns. 9plt.subplot(1, 2, 1) # First plot area (row 1, col 1 of 2, position 1). 10plt.plot(x1, y1) # Plot a line representing our first story. 11plt.title('Plot 1') # Adding title to our first plot 12 13x2 = np.array([0, 1, 2]) 14y2 = np.array([0, 2, 3]) 15plt.subplot(1, 2, 2) # Second plot area (row 1, col 2 of 2, position 2). 16plt.plot(x2, y2) # Next to it, a related tale. 17plt.title('Plot 2') # Adding title to our first plot 18 19plt.show() # Like turning the scrapbook page to view all photos.

Let's decipher plt.subplot(1, 2, 1): 1, 2 defines a grid of one row and two columns, and the last 1 specifies the first column for our plot. This ensures your plots are arranged like photos on a scrapbook page, telling parts of the bigger story side by side.

Subplots: Result

The resulting figure looks like this:

Placing two plots near help us to gather data visualization in one place making it easier for the viewers to compare and connect pieces of information.

Students Performance Dataset

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

Python
1first_student_marks = np.array([3.8, 3.9, 3.8, 4.1, 4.4, 4.2, 4.5, 4.5, 4.7]) 2second_student_marks = np.array([4, 3.9, 4.1, 4.1, 4.1, 3.9, 3.8, 3.7, 3.5]) 3semesters = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
Plotting Students Performance

Here is how we will plot these graphs:

Python
1fig = plt.figure() # Start a new figure 2 3# Begin a subplot grid: 1 row and 2 columns. 4plt.subplot(1, 2, 1) 5plt.ylim([3, 5]) 6plt.xticks([0, 3, 6, 9]) 7plt.xlabel('Semester') 8plt.ylabel('Mean Score') 9plt.plot(semesters, first_student_marks) 10plt.title('student A') 11 12plt.subplot(1, 2, 2) 13plt.ylim([3, 5]) 14plt.xticks([0, 3, 6, 9]) 15plt.xlabel('Semester') 16plt.ylabel('Mean Score') 17plt.plot(semesters, second_student_marks) 18plt.title('student B') 19 20plt.subplots_adjust(wspace=0.5) # Adjusting horizontal space 21fig.suptitle('students\' performance') # Adding main title to the whole figure 22 23plt.show()

Notice a couple of things. Firstly, plt.ylim function ensures plots have equal y-axis limits, making the comparison more clear. Secondly, the figure is saved in the fig variable, which lets us add a main title using fig.suptitle function. Finally, we use the new plt.subplots_adjust function with a variable wspace parameter to ensure there is enough place between the subplots.

Plotting Students Performance Result

Here is the result:

Having two plots side-to-side plots lets us both investigate individual graphs and easily compare them to each other.

Layering Plots on the Same Axis

There is another way to compare these plots.

To tell a rich story, we often combine multiple elements on the same page, like overlaying transparent leaves over a photo. Similarly, we can overlay plots on the same axis in Matplotlib, comparing different datasets directly.

Combining two plots on one axis is easy: call the plt.plot function twice!

Python
1plt.plot(semesters, first_student_marks, label='Student 1', color='purple') # Overlay Version A. 2plt.plot(semesters, second_student_marks, label='Student 2', color='orange') # Overlay Version B. 3plt.title('Students\' Performances') # Adding title to our plot 4plt.xlabel('Semester') 5plt.ylabel('Mean Score') 6 7plt.legend() # Clarify which line refers to each version. 8plt.show()
Result of the Plots Overlaying

Here is the result. Check out how we can compare two students' performances:

Notice that the plt.legend() function acts as a caption beneath our photo, helping readers understand which element is within the story's overlay.

Wrapping Up: Your Data Storybook Complete

Bravo! You're now equipped to craft a multi-layered data storybook with plots on the same axis and diverse visuals collected in one figure. Just as a scrapbook contains different pictures and embellishments on a page, using plt.subplots() and plt.figure(), you've learned to arrange different data plots to create multifaceted visual narratives in Python with Matplotlib.

As we close this chapter, get ready to apply your skills in the next round of practice exercises. By creating your own data stories, you'll solidify your understanding of these techniques and begin to see the bigger picture in your data. Your journey into eloquent data storytelling has only just begun!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.