Matplotlib Cheatsheet

Matplotlib is a powerful and versatile Python library for creating static, interactive, and publication-quality visualizations. It is widely used in data science, scientific research, engineering, finance, and many other fields for visualizing data and conveying insights.

With Matplotlib, we can create a wide range of plots, including line plots, scatter plots, bar plots, histograms, pie charts, heat maps, and more. Its flexibility and extensive customization options allow us to create visually appealing and informative plots tailored to our specific needs.

Importing Matplotlib

import matplotlib.pyplot as plt

Preparing the data

Preparing one-dimensional data

import numpy as np
# Method 1: Generate random data
x = np.random.rand(100)
y = np.random.rand(100)
# Method 2: Generate data using a mathematical function
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
# Method 3: Load data from CSV file
data = pd.read_csv('data.csv')
x = data['x']
y = data['y']
# Method 4: Manually create data
x = [1, 2, 3, 4, 5]
y = [5, 4, 3, 2, 1]
# Method 5: Fetch data from an API
response = requests.get('https://api.example.com/data')
data = response.json()
# Extract x and y values from the API response
x = [point['x'] for point in data]
y = [point['y'] for point in data]

Preparing two-dimensional data

import numpy as np
# Method 1: Using a meshgrid
# Define the range of x and y values
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
# Create a meshgrid
X, Y = np.meshgrid(x, y)
# Define a function to generate Z values (example: a saddle shape)
Z = X**2 - Y**2
# Method 2: Generate random matrix
data = np.random.rand(10, 10)
# Method 3: Use image for data
from PIL import Image
# Load an image
image = Image.open('image.jpg')
# Convert image to numpy array
data = np.array(image)

Creating plots

  1. Create a basic plot

x_values = [0,1,2,3,4,5]
y_values = [0,1,2,3,4,5]
plt.plot(x_values, y_values)
  1. Creating a line plot with a label and title

x_values = [0,1,2,3,4,5]
y_values = [0,1,2,3,4,5]
plt.plot(x_values, y_values, label='Data')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Line plot example')
plt.legend()
  1. Creating a scatter plot

x_values = [0,1,2,3,4,5]
y_values = [0,2,5,1,4,5]
plt.scatter(x_values, y_values)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Scatter plot example')
plt.legend()
  1. Creating a histogram

data = [10, 20, 30, 25, 15, 35, 40, 50, 45, 55, 60, 70, 80, 90, 95, 85, 100]
plt.hist(data, bins = 5) # Create the histogram with 5 bins
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Histogram example')
plt.legend()
  1. Creating a bar plot

X_axis = ['A', 'B', 'C', 'D', 'E']
Y_axis = [20, 35, 30, 25, 40]
plt.bar(X_axis, Y_axis)
plt.xlabel('X_axis')
plt.ylabel('Y_axis')
plt.title('Bar graph example')
plt.show()
  1. Creating a pie chart

sizes = [20, 30, 25, 15, 10] # Sizes of each slice
labels = ['A', 'B', 'C', 'D', 'E'] # Labels for each slice
# Create the pie chart
plt.figure(figsize=(6, 6)) # Set the figure size
plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90, colors=['skyblue', 'yellowgreen', 'orange', 'lightcoral', 'lightskyblue'])
plt.title('Pie Chart Example')
plt.show()
  1. Creating a heatmap

data = [[random.random() for _ in range(10)] for _ in range(10)] # Random 10x10 matrix
plt.figure(figsize=(8, 6)) # Set the figure size
plt.imshow(data, cmap='viridis', interpolation='nearest')
plt.colorbar() # Add colorbar
plt.title('Heatmap Example')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()

Figures and axes

The figure function with its defining parameters

# Create a new figure with specified parameters
fig = plt.figure(
num=1, # Figure number
figsize=(8, 6), # Figure size (in inches)
dpi=100, # Dots per inch (resolution)
facecolor='lightblue', # Background color
edgecolor='red', # Border color
frameon=False, # Display frame
tight_layout={'pad': 2} # Adjust subplot parameters
)
# Add a subplot
ax = fig.add_subplot(111)
ax.plot([1, 2, 3], [4, 5, 6])
# Set title and labels
ax.set_title('Line Plot')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
# Show the plot
plt.show()

Axes

Axes enable precise manual placement and customization of individual plots within a figure, like a grid of plots.

# Create a figure and axes using fig.add_axes()
fig = plt.figure()
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # [left, bottom, width, height]
# Plot something on the axes
ax.plot([1, 2, 3], [4, 5, 6])
ax.set_title('Using fig.add_axes()')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
# Create subplots using fig.add_subplot()
fig = plt.figure()
# Subplot 1
ax1 = fig.add_subplot(221)
ax1.plot([1, 2, 3], [4, 5, 6])
ax1.set_title('Subplot 1')
# Subplot 2
ax3 = fig.add_subplot(212)
ax3.plot([1, 2, 3], [4, 5, 6])
ax3.set_title('Subplot 2')
# Create subplots using plt.subplots()
fig3, axes = plt.subplots(nrows=2, ncols=2)
# Plot something on each subplot
for i in range(2):
for j in range(2):
axes[i, j].plot([1, 2, 3], [4, 5, 6])
axes[i, j].set_title(f'Subplot {i+1}{j+1}')
# Create subplots with a single row using plt.subplots()
fig4, axes2 = plt.subplots(ncols=3)
# Plot something on each subplot
for i in range(3):
axes2[i].plot([1, 2, 3], [4, 5, 6])
axes2[i].set_title(f'Subplot {i+1}')
# Adjust layout
plt.tight_layout()
# Show the plots
plt.show()

Customizing plots

  1. Customizing line style and colors

The different types of line styles available are '-', '--', '-.', ':'.

# Plot with custom line style and color
plt.plot([1, 2, 3], [4, 5, 6], linestyle='--', color='red', linewidth = 2, alpha = 0.5)
plt.show()
  1. Adding annotations and text

The different types of values for ha (horizontal alignment) are left, center and right. The different types of values for va (vertical alignment) are top, center and bottom.

plt.plot([1, 2, 3], [4, 5, 6])
plt.text(2, 5, 'Annotation', fontsize=12, ha='center', va='bottom')
plt.show()
  1. Changing marker style and size

The different type of marker styles available are 'o', 's', '^', 'x'.

plt.plot([1, 2, 3], [4, 5, 6], marker='o', markersize=10, markerfacecolor='blue', markeredgewidth=2, markeredgecolor='red')
plt.show()
  1. Customizing axis limits and labels

plt.plot([1, 2, 3], [4, 5, 6])
plt.xlim(0, 4)
plt.ylim(3, 7)
plt.xlabel('X-axis', fontsize=12)
plt.ylabel('Y-axis', fontsize=12)
plt.show()
  1. Setting plot title and legends

The different values available for font weight are normal, bold and light. The different values for loc are best, upper right, upper left, lower left, lower right, right, center left, center right, lower center, upper center and center.

plt.plot([1, 2, 3], [4, 5, 6], label='Data')
plt.title('Customized Plot', fontsize=14, fontweight='bold', color='green')
plt.legend(fontsize=12, loc='upper right')
plt.show()
  1. Changing figure size and resolution

plt.figure(figsize=(8, 6), dpi=100)
plt.plot([1, 2, 3], [4, 5, 6])
plt.show()
  1. Customizing tick mark and grids

plt.plot([1, 2, 3], [4, 5, 6])
plt.xticks([1, 2, 3], ['A', 'B', 'C'], fontsize=12)
plt.yticks(fontsize=12)
plt.grid(True, linestyle='--', linewidth=0.5)
plt.show()

Plotting techniques

For 1D data

# Generate sample data
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
# Create subplots
fig, axes = plt.subplots(2, 2)
# Plot lines connecting points
lines = axes[0, 0].plot(x, y)
# Scatter plot of unconnected points
axes[0, 0].scatter(x, y)
# Plot vertical bars
axes[0, 0].bar([1, 2, 3], [3, 4, 5])
# Plot horizontal bars
axes[1, 0].barh([0.5, 1, 2.5], [0, 1, 2])
# Draw a horizontal line
axes[1, 1].axhline(0.45)
# Draw a vertical line
axes[0, 1].axvline(0.65)
# Fill the area under the curve
axes[0, 1].fill(x, y, color='blue')
# Fill between the curve and the x-axis
axes[1, 1].fill_between(x, y, color='yellow')
# Set a different title for the entire plot
fig.suptitle('Exploring Matplotlib Plotting Methods', fontsize=16)
plt.show()

For 2D data

# Generate sample 2D data
data = np.random.rand(10, 10)
data1 = np.random.rand(10, 10)
data2 = np.random.rand(10, 10)
img = np.random.rand(10, 10)
# Create subplots
fig, axes2 = plt.subplots(1, 3)
# Display an image
im = axes2[0].imshow(img, cmap='viridis', interpolation='nearest', vmin=2, vmax=2)
axes2[0].set_title('Image')
# Plot pseudocolor plot of 2D array
axes2[1].pcolor(data2)
axes2[1].set_title('Pseudocolor Plot')
# Plot pseudocolor plot of 2D array
axes2[1].pcolormesh(data)
axes2[1].set_title('Pcolormesh Plot')
# Plot contours of 2D array
CS = axes2[2].contour(data1)
axes2[2].set_title('Contour Plot')
# Plot filled contours of 2D array
axes2[2].contourf(data1)
axes2[2].set_title('Filled Contour Plot')
# Label the contour plot
plt.clabel(CS, inline=True, fontsize=8)
plt.title('Contour Plot with Labels')
plt.show()

For vector patterns

# Sample data
X, Y = np.meshgrid(np.arange(-3, 3, 0.5), np.arange(-3, 3, 0.5))
U = -1 - X**2 + Y
V = 1 + X - Y**2
# Create subplots
fig, axes = plt.subplots(1, 3)
# Add an arrow to illustrate a direction
axes[0].arrow(0, 0, 0.5, 0.5)
axes[0].set_title('Directional Arrow')
# Plot a 2D field illustrating streamlines
axes[1].streamplot(X, Y, U, V)
axes[1].set_title('Streamlines')
# Plot a 2D field representing vector directions
axes[2].quiver(X, Y, U, V)
axes[2].set_title('Vector Field')
plt.show()

Saving and closing plot

plt.close() # Close current plot window
plt.close('MyPlotWindow') # Close specific plot window using its name
plt.close('all') # Close all plot windows
plt.clf() # Clear the figure
plt.cla() # Clear an axis
plt.savefig('plot.png', dpi=300) # Save plot as PNG file with 300 DPI
plt.savefig('plot.png', transparent=True) # Save plot with a transparent background
plt.savefig('plot.png', figsize=(8, 6)) # Save plot with a custom size
Saving and closing a plot

Copyright ©2024 Educative, Inc. All rights reserved