0
0
Matplotlibdata~30 mins

GridSpec for complex layouts in Matplotlib - Mini Project: Build & Apply

Choose your learning style9 modes available
GridSpec for complex layouts
📖 Scenario: You are creating a report with multiple charts arranged in a complex layout. Using matplotlib's GridSpec, you will place different plots in specific grid positions to make the report clear and organized.
🎯 Goal: Build a figure with a 3x3 grid layout using GridSpec. Place three plots: a line plot spanning the top row, a scatter plot in the bottom-left cell, and a bar plot spanning the bottom-right two cells.
📋 What You'll Learn
Create a 3x3 GridSpec layout
Place a line plot spanning the entire top row
Place a scatter plot in the bottom-left cell
Place a bar plot spanning the bottom-right two cells
Use plt.show() to display the figure
💡 Why This Matters
🌍 Real World
Data scientists often need to create reports with multiple charts arranged neatly to compare data visually.
💼 Career
Knowing how to use GridSpec helps you build professional and clear visualizations for presentations and dashboards.
Progress0 / 4 steps
1
Create a 3x3 GridSpec layout
Import matplotlib.pyplot as plt and GridSpec from matplotlib.gridspec. Then create a figure called fig with size (8, 6) and a GridSpec object called gs with 3 rows and 3 columns.
Matplotlib
Need a hint?

Use plt.figure(figsize=(8, 6)) to create the figure and GridSpec(3, 3, figure=fig) to create the grid layout.

2
Add a line plot spanning the top row
Create an axes called ax1 using fig.add_subplot(gs[0, :]) to span the entire top row. Plot a line with x values [0, 1, 2, 3] and y values [10, 20, 25, 30] on ax1.
Matplotlib
Need a hint?

Use gs[0, :] to select the entire first row for the line plot.

3
Add a scatter plot in the bottom-left cell
Create an axes called ax2 using fig.add_subplot(gs[2, 0]) for the bottom-left cell. Plot a scatter plot with x values [1, 2, 3] and y values [4, 5, 6] on ax2.
Matplotlib
Need a hint?

Use gs[2, 0] to select the bottom-left cell for the scatter plot.

4
Add a bar plot spanning the bottom-right two cells and display the figure
Create an axes called ax3 using fig.add_subplot(gs[2, 1:]) to span the bottom-right two cells. Plot a bar chart with categories ["A", "B", "C"] and values [5, 7, 3] on ax3. Finally, use plt.show() to display the figure.
Matplotlib
Need a hint?

Use gs[2, 1:] to select the bottom-right two cells for the bar plot. Use plt.show() to display the figure.