Matplotlib Pyplot

Master the pyplot interface for easy plotting

🎨 Understanding Pyplot

Pyplot is matplotlib's state-based interface that makes plotting as easy as MATLAB. It provides a simple way to create plots with just a few lines of code.


import matplotlib.pyplot as plt

# Simple pyplot example
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.ylabel('Values')
plt.xlabel('Numbers')
plt.title('Simple Plot')
plt.show()
                                    
Simple
Interface
MATLAB
Like
State
Based

🎯 Pyplot Basics

📊

State-Based

Keeps track of current figure and axes

plt.plot([1, 2, 3])
plt.title('Auto Current Figure')
🎨

Easy Styling

Simple commands for colors and styles

plt.plot([1, 2, 3], 'ro-')
plt.grid(True)
🏷️

Quick Labels

Add titles and labels easily

plt.xlabel('X axis')
plt.ylabel('Y axis')
plt.title('My Plot')
💾

Save & Show

Display or save with one command

plt.show()
plt.savefig('plot.png')

🔹 Basic Pyplot Commands

Essential pyplot functions for creating plots

import matplotlib.pyplot as plt

# Create data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

# Basic plot
plt.plot(x, y)

# Add labels and title
plt.xlabel('X values')
plt.ylabel('Y values') 
plt.title('Basic Pyplot Example')

# Add grid
plt.grid(True)

# Show the plot
plt.show()

# Save the plot
plt.savefig('my_plot.png')

🔹 Figure and Axes Management

Control figures and subplots with pyplot

# Create new figure
plt.figure(figsize=(10, 6))

# Plot on current figure
plt.plot([1, 2, 3], [1, 4, 9], label='Line 1')
plt.plot([1, 2, 3], [1, 2, 3], label='Line 2')

# Add legend
plt.legend()

# Create subplots
plt.figure(figsize=(12, 4))

# First subplot
plt.subplot(1, 3, 1)
plt.plot([1, 2, 3], [1, 4, 9])
plt.title('Plot 1')

# Second subplot  
plt.subplot(1, 3, 2)
plt.plot([1, 2, 3], [1, 2, 3])
plt.title('Plot 2')

# Third subplot
plt.subplot(1, 3, 3)
plt.plot([1, 2, 3], [3, 2, 1])
plt.title('Plot 3')

plt.tight_layout()
plt.show()

🔹 Pyplot vs Object-Oriented

Understanding the two matplotlib interfaces

🎨 Pyplot Interface (State-based)

  • Simple and MATLAB-like
  • Good for quick plots and scripts
  • Automatically manages current figure

🔧 Object-Oriented Interface

  • More control and flexibility
  • Better for complex applications
  • Explicit figure and axes objects
# Pyplot style (state-based)
plt.plot([1, 2, 3], [1, 4, 9])
plt.title('Pyplot Style')
plt.show()

# Object-oriented style
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [1, 4, 9])
ax.set_title('Object-Oriented Style')
plt.show()

# Both produce the same result!

🔹 Common Pyplot Functions

Most frequently used pyplot commands

import matplotlib.pyplot as plt
import numpy as np

# Sample data
x = np.linspace(0, 10, 100)
y = np.sin(x)

# Plotting functions
plt.plot(x, y)              # Line plot
plt.scatter([1, 2, 3], [1, 4, 9])  # Scatter plot
plt.bar(['A', 'B', 'C'], [1, 2, 3])  # Bar chart

# Labeling functions
plt.title('My Plot')        # Title
plt.xlabel('X Label')       # X-axis label
plt.ylabel('Y Label')       # Y-axis label
plt.legend(['Line 1'])      # Legend

# Appearance functions
plt.grid(True)              # Grid
plt.xlim(0, 10)            # X-axis limits
plt.ylim(-1, 1)            # Y-axis limits

# Output functions
plt.show()                  # Display plot
plt.savefig('plot.png')     # Save plot
plt.close()                 # Close figure

🔹 Interactive Features

Pyplot's interactive capabilities

# Interactive mode
plt.ion()  # Turn on interactive mode

# Create plot
plt.plot([1, 2, 3], [1, 4, 9])
plt.draw()  # Update plot

# Add more data
plt.plot([1, 2, 3], [1, 2, 3])
plt.draw()

# Turn off interactive mode
plt.ioff()

# Pause execution (useful in scripts)
plt.pause(2)  # Pause for 2 seconds

# Wait for user input
plt.waitforbuttonpress()  # Wait for key press or mouse click

🧠 Test Your Knowledge

What does plt.subplot(2, 2, 1) create?

Which command saves a plot to file?

What is pyplot's main characteristic?