Introduction to Subplots in Matplotlib
• Definition: Subplots are smaller axes grouped
within a single figure, allowing multiple views
of data side-by-side.
• Uses: Helpful for comparing different datasets
or visualizations together.
• Example Code:
• import matplotlib.pyplot as plt
• import numpy as np
Creating Basic Subplots with Axes
• Standard Axes:
• ax1 = plt.axes() # Creates main axes
• ax2 = plt.axes([0.65, 0.65, 0.2, 0.2]) # Inset subplot
• Figure with Custom Axes:
• fig = plt.figure()
• ax1 = fig.add_axes([0.1, 0.5, 0.8, 0.4], ylim=(-1.2, 1.2))
• ax2 = fig.add_axes([0.1, 0.1, 0.8, 0.4], ylim=(-1.2, 1.2))
• x = np.linspace(0, 10)
• ax1.plot(np.sin(x))
• ax2.plot(np.cos(x))
Output:
Using plt.subplot for Simple Grids
• Definition: plt.subplot(rows, cols, index) creates
subplots in a grid layout.
• Example Code:
• for i in range(1, 7):
• plt.subplot(2, 3, i)
• plt.text(0.5, 0.5, str((2, 3, i)), fontsize=18,
ha='center')
• Explanation: The grid layout makes it easy to organize
multiple subplots in a matrix format.
Output:
Flexible Grids with GridSpec
• Definition: GridSpec allows subplots to span multiple
rows/columns.
• Example Code:
• grid = plt.GridSpec(2, 3, wspace=0.4, hspace=0.3)
• plt.subplot(grid[0, 0]) # First row, first column
• plt.subplot(grid[0, 1:]) # First row, spans columns 2 and 3
• plt.subplot(grid[1, 2]) # Second row, third column
• Explanation: More control over layout with Python slicing.
Output:

Subplots_in_Matplotlib_Presentation-1.pptx

  • 1.
    Introduction to Subplotsin Matplotlib • Definition: Subplots are smaller axes grouped within a single figure, allowing multiple views of data side-by-side. • Uses: Helpful for comparing different datasets or visualizations together. • Example Code: • import matplotlib.pyplot as plt • import numpy as np
  • 2.
    Creating Basic Subplotswith Axes • Standard Axes: • ax1 = plt.axes() # Creates main axes • ax2 = plt.axes([0.65, 0.65, 0.2, 0.2]) # Inset subplot • Figure with Custom Axes: • fig = plt.figure() • ax1 = fig.add_axes([0.1, 0.5, 0.8, 0.4], ylim=(-1.2, 1.2)) • ax2 = fig.add_axes([0.1, 0.1, 0.8, 0.4], ylim=(-1.2, 1.2)) • x = np.linspace(0, 10) • ax1.plot(np.sin(x)) • ax2.plot(np.cos(x))
  • 3.
  • 4.
    Using plt.subplot forSimple Grids • Definition: plt.subplot(rows, cols, index) creates subplots in a grid layout. • Example Code: • for i in range(1, 7): • plt.subplot(2, 3, i) • plt.text(0.5, 0.5, str((2, 3, i)), fontsize=18, ha='center') • Explanation: The grid layout makes it easy to organize multiple subplots in a matrix format.
  • 5.
  • 6.
    Flexible Grids withGridSpec • Definition: GridSpec allows subplots to span multiple rows/columns. • Example Code: • grid = plt.GridSpec(2, 3, wspace=0.4, hspace=0.3) • plt.subplot(grid[0, 0]) # First row, first column • plt.subplot(grid[0, 1:]) # First row, spans columns 2 and 3 • plt.subplot(grid[1, 2]) # Second row, third column • Explanation: More control over layout with Python slicing.
  • 7.