Mastering Matplotlib

An interactive infographic for the 80/20 of Visualization in Python.

🖌 Matplotlib Master Reference Table

Your quick guide to essential plotting. Click any function to go directly to the official Matplotlib documentation.

📚 Key Documentation Links

Matplotlib API Reference → The main index page for the entire Matplotlib library.

Pyplot Reference → A summary of all functions in the high-level `pyplot` interface.

Axes API Reference → The full list of methods for customizing individual plots (Axes).

Critical Functions (The Essentials)

The absolute must-knows for creating any plot.

plt.figure()plt.subplots()plt.plot()plt.scatter()plt.bar()plt.hist()plt.show()plt.savefig()

Important Functions (Labels & Style)

Essential for making your plots readable and professional.

plt.title()plt.xlabel()plt.ylabel()plt.legend()plt.grid()plt.xlim()plt.ylim()plt.style.use()

Recommended Learning Path

A structured approach to learning Matplotlib effectively.

1

Create a Plot

plt.plot(x, y), plt.show()

2

Add Labels

plt.title(), xlabel(), ylabel()

3

Customize

color, marker, linestyle, legend()

4

Save & Share

plt.savefig('my_plot.png')

Core Plotting Functions

The workhorses of Matplotlib for creating different types of visualizations.

plt.plot()

Creates line plots to show trends over continuous data.

plt.scatter()

Visualizes the relationship between two numeric variables.

plt.bar()

Compares quantities across different categories.

plt.hist()

Shows the distribution of a single numeric variable by binning data.

Full A-Z Quick Reference

A searchable list of the most common Matplotlib functions.

Function / Method Description

Critical Functions (The 20% You'll Use 80% of the Time)

These represent the absolute minimum needed to create, configure, and display basic visualizations. Without these, Matplotlib couldn't fulfill its primary purpose of creating and saving plots. They're used in over 80% of Matplotlib scripts.

plot()

Primary function for line/marker plots.

plt.plot(x, y, 'r-o')

scatter()

Essential for point cloud visualization.

plt.scatter(x, y, c=colors)

imshow()

Core image display capability.

plt.imshow(matrix)

subplots()

Fundamental figure/axes creation.

fig, ax = plt.subplots()

show()

Required to display any visualization.

plt.show()

savefig()

Critical for output/saving results.

plt.savefig('figure.png')

xlabel() / ylabel()

Basic plot labeling for context.

plt.xlabel('Time (s)')
X-LabelY-Label

title()

Essential plot identification.

plt.title('Performance')
Title

legend()

Key for identifying multiple data series.

plt.legend()
AB

xlim() / ylim()

Fundamental axis range control.

plt.xlim([0, 100])
0100
```

Important Functions (The Supporting Cast)

These functions support and extend the core functionality, enabling more sophisticated and professional-quality plots. While not used in every script, they are frequently needed for customization, specialized visualizations, and fine-tuned layout control.

figure()

Advanced figure management and creation.

fig = plt.figure(figsize=(10, 8))

bar() / barh()

Fundamental chart types for categorical data.

plt.bar(categories, values)

hist()

Key for understanding data distribution.

plt.hist(data, bins=30)

contour() / contourf()

For visualizing 3D surfaces in 2D.

plt.contourf(X, Y, Z)

grid()

Common and useful plot enhancement.

plt.grid(True, linestyle=':')

axhline() / axvline()

Crucial for adding reference lines.

plt.axhline(0, color='grey')

text() / annotate()

For adding detailed plot annotations.

plt.text(x, y, 'Important Point')
Note

fill_between()

Highlights areas, like confidence intervals.

plt.fill_between(x, y1, y2)

boxplot()

Standard for statistical distribution summary.

plt.boxplot(data_collection)

pie()

Common chart type for proportions.

plt.pie(sizes, labels=labels)

xticks() / yticks()

Essential for custom tick mark control.

plt.xticks([0, 5, 10], ['A', 'B', 'C'])
ABC

colorbar()

Important for heatmaps and contour plots.

plt.colorbar(mappable)
```

Utility Functions (Specialized & Niche Tools)

These functions handle edge cases, very specific visualization types, or provide convenience wrappers. Many are used in less than 1% of scripts or are specialized for particular scientific or engineering domains.

acorr()

Specialized statistical plot for autocorrelation.

plt.acorr(signal, maxlags=10)

arrow()

For drawing a single, styled arrow on a plot.

plt.arrow(x, y, dx, dy)

axhspan() / axvspan()

Niche highlighting for specific data ranges.

plt.axhspan(ymin, ymax, color='b')

specgram()

Specialized for signal processing visualizations.

plt.specgram(x, Fs=2)

spy()

Visualizes the sparsity pattern of a matrix.

plt.spy(sparse_matrix)

stackplot()

For creating specialized stacked area charts.

plt.stackplot(x, y1, y2)

violinplot()

Advanced statistical distribution visualization.

plt.violinplot(dataset)

hexbin()

Specialized 2D histogram for dense data.

plt.hexbin(x, y, gridsize=20)

errorbar()

Specialized visualization for data with errors.

plt.errorbar(x, y, yerr=err)
```

Detailed Function Inventory

A visual guide to the top 50 functions in matplotlib.pyplot.

acorr()

Plot the autocorrelation of a sequence.

plt.acorr(x, maxlags=10)

annotate()

Add a text annotation with an optional arrow.

plt.annotate('Peak', xy=(2, 1))
Peak

arrow()

Add a single arrow to the axes.

plt.arrow(0, 0, 0.5, 0.5)

autoscale()

Autoscale the axis view to fit the data.

plt.autoscale(enable=True)

axhline()

Add a horizontal line across the axes.

plt.axhline(y=0.5, color='r')

axvline()

Add a vertical line across the axes.

plt.axvline(x=0.5, color='r')

axhspan()

Add a horizontal span (rectangle) across axes.

plt.axhspan(0.25, 0.75, color='g')

axvspan()

Add a vertical span (rectangle) across axes.

plt.axvspan(0.25, 0.75, color='g')

bar()

Make a vertical bar plot.

plt.bar(['A', 'B', 'C'], [3, 5, 2])

barh()

Make a horizontal bar plot.

plt.barh(['A', 'B', 'C'], [3, 5, 2])

boxplot()

Make a box and whisker plot.

plt.boxplot(data)

cla()

Clear the current axes.

plt.cla()

clf()

Clear the current figure.

plt.clf()

close()

Close a figure window.

plt.close()

colorbar()

Add a colorbar to a plot.

plt.colorbar()

contour() / contourf()

Plot contour lines or filled contours.

plt.contourf(X, Y, Z)

figure()

Create a new figure.

fig = plt.figure(figsize=(8,6))

grid()

Configure and display grid lines.

plt.grid(True, linestyle='--')

hist()

Plot a histogram.

plt.hist(data, bins=20)

imshow()

Display data as an image.

plt.imshow(image_array)

legend()

Place a legend on the axes.

plt.legend(['Line A', 'Line B'])
A

plot()

Plot lines and/or markers.

plt.plot(x, y, 'r-o')

pie()

Make a pie chart.

plt.pie([10, 20, 5])

savefig()

Save the current figure to a file.

plt.savefig('my_plot.png')

scatter()

Make a scatter plot.

plt.scatter(x, y)

show()

Display all open figures.

plt.show()

subplots()

Create a figure and a set of subplots.

fig, axes = plt.subplots(2, 2)

title() / xlabel() / ylabel()

Set title and labels for axes.

plt.title('My Plot')
TitleX-LabelY-Label

xlim() / ylim() / xticks() ...

Set axis limits and tick locations/labels.

plt.xlim(0, 10)
010
```

📊 Matplotlib Plotting Examples

From a Pandas DataFrame to beautiful visualizations.

Step 1: The Sample Dataset

Monthly Sales Data

Month Product A Product B Product C
Jan150200180
Feb180210190
Mar170220200
Apr160230210
May190240220

Create DataFrame

First, we load this data into a Pandas DataFrame.

import pandas as pd

data = {
    "Month": ["Jan", "Feb", "Mar", "Apr", "May"],
    "Product A": [150, 180, 170, 160, 190],
    "Product B": [200, 210, 220, 230, 240],
    "Product C": [180, 190, 200, 210, 220]
}
df = pd.DataFrame(data)

Step 2: Plotting with Figures & Subplots

Creating Subplots

Use `plt.subplots()` to create a figure with multiple plotting areas (Axes).

import matplotlib.pyplot as plt

fig, axes = plt.subplots(3, 1, figsize=(8, 10), sharex=True)

# Plot for Product A
axes[0].plot(df["Month"], df["Product A"], marker='o', color='r')
axes[0].set_title("Product A Sales")
axes[0].set_ylabel("Units Sold")

# Plot for Product B
axes[1].plot(df["Month"], df["Product B"], marker='s', color='g')
axes[1].set_title("Product B Sales")
axes[1].set_ylabel("Units Sold")

# Plot for Product C
axes[2].plot(df["Month"], df["Product C"], marker='^', color='b')
axes[2].set_title("Product C Sales")
axes[2].set_xlabel("Month")

plt.tight_layout()
plt.show()

Subplots Visualization

Product A Sales

Product B Sales

Product C Sales

Step 3: Other Common Plot Types

Scatter Plot

plt.scatter(df["Month"], df["Product A"], c='r', label='A')
plt.scatter(df["Month"], df["Product B"], c='g', label='B')
plt.scatter(df["Month"], df["Product C"], c='b', label='C')
plt.title("Monthly Sales Scatter Plot")
plt.legend()
plt.show()

Scatter Plot Visualization

Bar Plot

df.plot(
    x="Month", 
    y=["Product A", "Product B", "Product C"], 
    kind='bar', 
    figsize=(8,5),
    title="Monthly Sales Bar Plot"
)
plt.show()

Bar Plot Visualization

Histogram

plt.hist(
    df["Product A"], 
    bins=5, 
    color='orange', 
    edgecolor='black'
)
plt.title("Histogram of Product A Sales")
plt.show()

Histogram Visualization