0
0
Data Analysis Pythondata~15 mins

Subplots for multiple charts in Data Analysis Python - Deep Dive

Choose your learning style9 modes available
Overview - Subplots for multiple charts
What is it?
Subplots allow you to place multiple charts in a single figure, arranged in rows and columns. This helps compare different data visuals side by side without opening many separate windows. Each subplot can show a different chart type or dataset, making analysis clearer and more organized. It is a common technique in data visualization to present multiple views together.
Why it matters
Without subplots, you would need to create many separate charts, which can be confusing and hard to compare. Subplots save space and make it easier to spot patterns or differences across datasets. They help communicate insights more effectively by grouping related visuals. This is especially important when presenting findings to others or exploring complex data.
Where it fits
Before learning subplots, you should know how to create basic charts using libraries like Matplotlib or Seaborn. After mastering subplots, you can explore advanced visualization techniques like interactive dashboards or animation. Subplots are a foundational skill in the data visualization journey.
Mental Model
Core Idea
Subplots are like a grid of small windows, each showing a different chart, all inside one big picture frame.
Think of it like...
Imagine a photo collage frame with multiple slots. Each slot holds a different photo, but together they tell a bigger story. Subplots work the same way by holding different charts in one figure.
┌───────────────┬───────────────┐
│   Chart 1     │   Chart 2     │
├───────────────┼───────────────┤
│   Chart 3     │   Chart 4     │
└───────────────┴───────────────┘
Build-Up - 7 Steps
1
FoundationCreating a single basic plot
🤔
Concept: Learn how to make a simple chart using Matplotlib.
import matplotlib.pyplot as plt x = [1, 2, 3, 4] y = [10, 20, 25, 30] plt.plot(x, y) plt.title('Simple Line Chart') plt.show()
Result
A window opens showing a line chart with points connected by lines.
Understanding how to create a single plot is the first step before combining multiple plots.
2
FoundationUnderstanding figure and axes objects
🤔
Concept: Learn about the figure (the whole image) and axes (individual plot areas) in Matplotlib.
import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot([1, 2, 3], [4, 5, 6]) ax.set_title('Plot on Axes Object') plt.show()
Result
A plot appears inside a figure window, controlled by the axes object.
Knowing figure and axes helps control where and how plots appear, which is key for subplots.
3
IntermediateCreating multiple subplots in one figure
🤔Before reading on: do you think subplots create separate windows or one combined window? Commit to your answer.
Concept: Use plt.subplots() with parameters to create multiple plots arranged in a grid inside one figure.
fig, axs = plt.subplots(2, 2) # 2 rows, 2 columns axs[0, 0].plot([1, 2, 3], [1, 4, 9]) axs[0, 0].set_title('Plot 1') axs[0, 1].bar([1, 2, 3], [3, 5, 7]) axs[0, 1].set_title('Plot 2') axs[1, 0].scatter([1, 2, 3], [7, 8, 9]) axs[1, 0].set_title('Plot 3') axs[1, 1].hist([1, 2, 2, 3, 3, 3]) axs[1, 1].set_title('Plot 4') plt.tight_layout() plt.show()
Result
One window shows four different charts arranged in a 2x2 grid.
Creating multiple subplots in one figure helps compare different charts side by side efficiently.
4
IntermediateCustomizing subplot layout and size
🤔Before reading on: do you think subplot sizes are fixed or adjustable? Commit to your answer.
Concept: Adjust figure size and spacing between subplots for better readability and presentation.
fig, axs = plt.subplots(1, 3, figsize=(12, 4)) # 1 row, 3 columns for i, ax in enumerate(axs): ax.plot([1, 2, 3], [j*(i+1) for j in [1, 2, 3]]) ax.set_title(f'Plot {i+1}') plt.subplots_adjust(wspace=0.5) # space between plots plt.show()
Result
A wide figure with three plots spaced apart horizontally.
Adjusting size and spacing improves clarity and prevents overlapping labels or titles.
5
IntermediateSharing axes between subplots
🤔Before reading on: do you think each subplot has independent axes by default? Commit to your answer.
Concept: Link x or y axes across subplots to synchronize scales and zooming.
fig, axs = plt.subplots(2, 2, sharex=True, sharey=True) for ax in axs.flat: ax.plot([1, 2, 3], [1, 4, 9]) ax.set_title('Shared Axes') plt.tight_layout() plt.show()
Result
Four plots with the same x and y axis scales, making comparison easier.
Sharing axes helps spot differences or similarities by using a common scale.
6
AdvancedUsing gridspec for complex subplot layouts
🤔Before reading on: do you think subplot grids must be uniform in size? Commit to your answer.
Concept: Gridspec allows flexible subplot sizes and positions within a figure.
import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec fig = plt.figure(figsize=(8, 6)) gs = gridspec.GridSpec(3, 3) ax1 = fig.add_subplot(gs[0, :]) # top row, all columns ax2 = fig.add_subplot(gs[1, :-1]) # middle row, first two columns ax3 = fig.add_subplot(gs[1:, -1]) # last column, last two rows ax4 = fig.add_subplot(gs[-1, 0]) # bottom row, first column ax1.plot([1, 2, 3], [1, 2, 3]) ax1.set_title('Wide Top Plot') ax2.bar([1, 2, 3], [3, 2, 1]) ax3.scatter([1, 2, 3], [3, 2, 1]) ax4.hist([1, 2, 2, 3, 3, 3]) plt.tight_layout() plt.show()
Result
A figure with subplots of different sizes arranged in a custom grid.
Gridspec unlocks advanced layout control beyond simple rows and columns.
7
ExpertEmbedding subplots in interactive dashboards
🤔Before reading on: do you think static subplots can be interactive? Commit to your answer.
Concept: Combine subplots with interactive tools like widgets or Plotly for dynamic data exploration.
import matplotlib.pyplot as plt from matplotlib.widgets import Slider fig, ax = plt.subplots() plt.subplots_adjust(bottom=0.25) x = [1, 2, 3, 4, 5] y = [1, 4, 9, 16, 25] line, = ax.plot(x, y) ax_slider = plt.axes([0.25, 0.1, 0.65, 0.03]) slider = Slider(ax_slider, 'Scale', 0.1, 2.0, valinit=1) def update(val): scale = slider.val line.set_ydata([i * scale for i in y]) fig.canvas.draw_idle() slider.on_changed(update) plt.show()
Result
A plot with a slider that changes the scale of the data dynamically.
Integrating interactivity with subplots enhances user engagement and deeper data insight.
Under the Hood
Matplotlib creates a Figure object as the canvas for all plots. Each subplot is an Axes object placed inside the Figure at a specific position and size. When you call plt.subplots(), it creates the Figure and a grid of Axes arranged according to your parameters. Each Axes manages its own data, labels, and drawing commands. The Figure manages the overall layout and rendering. When you call plt.show(), the Figure renders all Axes together in one window.
Why designed this way?
This design separates the overall image (Figure) from individual plots (Axes) to give fine control over layout and content. Early plotting libraries mixed these concepts, making complex layouts hard. Matplotlib's approach allows flexible arrangements and easy customization. Alternatives like gridspec were added later to handle more complex layouts beyond uniform grids.
┌───────────────────────────────┐
│           Figure              │
│  ┌─────────┐  ┌─────────┐     │
│  │ Axes 1  │  │ Axes 2  │     │
│  └─────────┘  └─────────┘     │
│  ┌─────────┐  ┌─────────┐     │
│  │ Axes 3  │  │ Axes 4  │     │
│  └─────────┘  └─────────┘     │
└───────────────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do subplots create separate windows or one combined window? Commit to your answer.
Common Belief:Subplots open multiple separate windows for each chart.
Tap to reveal reality
Reality:Subplots create multiple charts inside one single window or figure.
Why it matters:Believing they open separate windows leads to inefficient workflows and confusion when trying to compare charts.
Quick: Do all subplots share the same axis scales by default? Commit to your answer.
Common Belief:All subplots automatically share the same x and y axis scales.
Tap to reveal reality
Reality:By default, each subplot has independent axes unless you specify sharing.
Why it matters:Assuming shared axes can cause misinterpretation of data comparisons if scales differ.
Quick: Can subplot layouts only be uniform grids? Commit to your answer.
Common Belief:Subplots must be arranged in equal-sized rows and columns.
Tap to reveal reality
Reality:Using tools like gridspec, subplots can have different sizes and positions.
Why it matters:Limiting to uniform grids restricts effective visualization of complex data layouts.
Quick: Are subplots always static images? Commit to your answer.
Common Belief:Subplots are static and cannot be interactive.
Tap to reveal reality
Reality:Subplots can be combined with interactive widgets or libraries for dynamic visuals.
Why it matters:Ignoring interactivity misses opportunities for deeper data exploration and user engagement.
Expert Zone
1
Subplots can be nested by creating figures inside figures using inset axes for detailed zooms or highlights.
2
Adjusting subplot parameters like aspect ratio and DPI affects both visual clarity and file size in saved figures.
3
Combining subplots with different plotting libraries (e.g., Matplotlib and Seaborn) requires careful management of axes to avoid conflicts.
When NOT to use
Avoid subplots when you need fully interactive, web-based dashboards; use tools like Plotly Dash or Bokeh instead. Also, for very large numbers of charts, consider pagination or separate figures to maintain clarity.
Production Patterns
Professionals use subplots to create summary dashboards in reports, compare model results side by side, and visualize multi-dimensional data slices. Automated scripts generate subplots for batch analysis, and gridspec is used for custom report layouts.
Connections
Dashboard Design
Subplots are a building block for dashboards, organizing multiple visuals in one view.
Understanding subplots helps grasp how dashboards arrange and synchronize multiple charts for user-friendly data exploration.
User Interface Layouts
Both use grid systems to arrange elements neatly and responsively.
Knowing subplot grids clarifies how UI frameworks manage component placement, improving design skills beyond data science.
Photography Collages
Subplots and collages both arrange multiple images in a single frame to tell a story.
Seeing subplots as collages helps appreciate the importance of layout and balance in visual communication.
Common Pitfalls
#1Overlapping labels and titles in subplots.
Wrong approach:fig, axs = plt.subplots(2, 2) for ax in axs.flat: ax.plot([1, 2, 3], [1, 4, 9]) ax.set_title('Title') plt.show()
Correct approach:fig, axs = plt.subplots(2, 2) for ax in axs.flat: ax.plot([1, 2, 3], [1, 4, 9]) ax.set_title('Title') plt.tight_layout() plt.show()
Root cause:Not adjusting layout spacing causes text to overlap and become unreadable.
#2Trying to plot on a single axes object when multiple subplots exist.
Wrong approach:fig, axs = plt.subplots(2, 2) plt.plot([1, 2, 3], [1, 4, 9]) # plots on default axes, not subplots plt.show()
Correct approach:fig, axs = plt.subplots(2, 2) axs[0, 0].plot([1, 2, 3], [1, 4, 9]) # plot on specific subplot plt.show()
Root cause:Confusing the global plt.plot with axes-specific plotting leads to missing or misplaced charts.
#3Assuming sharex/sharey automatically adjusts axis limits dynamically.
Wrong approach:fig, axs = plt.subplots(2, 1, sharex=True) axs[0].plot([1, 2, 3], [10, 20, 30]) axs[1].plot([1, 2, 3], [100, 200, 300]) plt.show()
Correct approach:fig, axs = plt.subplots(2, 1, sharex=True) axs[0].plot([1, 2, 3], [10, 20, 30]) axs[1].plot([1, 2, 3], [100, 200, 300]) axs[0].set_ylim(0, 350) plt.show()
Root cause:Sharing axes links ticks but does not automatically scale limits to fit all data.
Key Takeaways
Subplots let you organize multiple charts in one figure, making comparisons easier and clearer.
Each subplot is an independent plot area inside a figure, controlled by axes objects.
You can customize layout, size, spacing, and axis sharing to improve readability and insight.
Advanced tools like gridspec allow flexible, non-uniform subplot arrangements.
Combining subplots with interactivity unlocks powerful data exploration capabilities.