Bytes
ArrowsREWIND Our 2024 Journey

How AlmaBetter created an

IMPACT! Arrows
Data Science

Matplotlib Cheat Sheet (Basics to Advanced)

Last Updated: 21st January, 2025
icon

Arunav Goswami

Data Science Consultant at almaBetter

Learn key Matplotlib functions with our Matplotlib cheat sheet. Includes examples, advanced customizations and comparison with Seaborn for better visualizations

Matplotlib is a versatile library in Python used for data visualization. Matplotlib enables the creation of static, interactive, and animated visualizations in Python. It is highly customizable and integrates well with libraries like Pandas and NumPy. Its pyplot module simplifies the process of creating plots similar to MATLAB. This Matplotlib cheat sheet provides an overview of the essential functions, features, and tools available in Matplotlib, along with comparisons to Seaborn where relevant.

Key Matplotlib Modules and Basics

  • Pyplot Module: The interface to Matplotlib, mirroring MATLAB-like plotting commands.
  • Figure: The overall container for all plots.
  • Axes: The area where data is plotted, allowing for multiple subplots.
  • Artist: All graphical elements in Matplotlib.

Basic Setup

Importing Matplotlib

import matplotlib.pyplot as plt

Creating a Figure and Axes

fig, ax = plt.subplots(figsize=(width, height))
  • fig: The overall figure.
  • ax: The individual subplot (axes) in the figure.

Displaying a Plot

plt.show()

Figure and Axes

Creating Subplots

fig, axs = plt.subplots(nrows, ncols, figsize=(width, height))

Use axs as a 2D array for multiple subplots:

axs[row, col].plot(x, y)

Adjusting Layout

plt.tight_layout()

Adding a Title

fig.suptitle('Main Title', fontsize=16)

Matplotlib Plot Cheat Sheet

Line Plot

plt.plot(x, y, label='Label', color='blue', linestyle='-', marker='o')

Parameters:

  • color: 'blue', '#FF5733'
  • linestyle: '-', '--', ':', '-.'
  • marker: 'o', 's', '*', '.', '^'

Scatter Plot

plt.scatter(x, y, c='red', s=40, alpha=0.5, label='Label')
  • c: Marker color
  • s: Marker size
  • alpha: Transparency

Bar Plot

plt.bar(categories, values, color='green', alpha=0.7, label='Label')

Horizontal Bar Plot

plt.barh(categories, values, color='purple', alpha=0.7, label='Label')

Histogram

plt.hist(data, bins=10, color='gray', alpha=0.8, label='Histogram')

Pie Chart

plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90)

Optional Parameters:

  • explode: Tuple to offset slices (e.g., (0.1, 0, 0, 0)).

Box Plot

plt.boxplot(data, vert=True, patch_artist=True)

Heatmap (using imshow)

plt.imshow(data, cmap='viridis', interpolation='nearest')

Axes Customization

Adding Titles and Labels

ax.set_title('Title')
ax.set_xlabel('X-axis Label')
ax.set_ylabel('Y-axis Label')

Setting Limits

ax.set_xlim([xmin, xmax])
ax.set_ylim([ymin, ymax])

Adding Grid

ax.grid(True, which='both', linestyle='--', linewidth=0.5)

Adding Ticks

ax.set_xticks([x1, x2, x3])
ax.set_yticks([y1, y2, y3])

Rotating Ticks

plt.xticks(rotation=45)

Legends

Adding a Legend

ax.legend(loc='upper right', fontsize='small')
loc: 'upper left', 'upper right', 'lower left', 'lower right'

Annotations

Adding Text

ax.text(x, y, 'Text', fontsize=12, color='red', ha='center', va='center')

Adding Arrows

ax.annotate('Annotation', xy=(x, y), xytext=(x_text, y_text),
            arrowprops=dict(facecolor='black', shrink=0.05))

Styles

Predefined Styles

plt.style.use('ggplot')

Popular styles: 'seaborn', 'fivethirtyeight', 'classic'

Saving Plots

Save as File

plt.savefig('filename.png', dpi=300, bbox_inches='tight')

3D Plots (using mpl_toolkits.mplot3d)

Import and Create 3D Axes

from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

3D Line Plot

ax.plot3D(x, y, z, color='blue')

3D Scatter Plot

ax.scatter3D(x, y, z, c=z, cmap='Greens')

Advanced Features

Logarithmic Scale

ax.set_xscale('log')
ax.set_yscale('log')

Twin Axes

ax2 = ax.twinx()
ax2.plot(x, y, color='green')

Multiple Y-Axes

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(x, y, 'g-')
ax2.plot(x, np.cos(x), 'b--')

Customizing Colormaps

from matplotlib import cm
cmap = cm.get_cmap('viridis')
plt.scatter(x, y, c=z, cmap=cmap)

Tips for Debugging

  • Use plt.clf() to clear the current figure.
  • Use plt.close() to close a figure.

Object-Oriented vs. Pyplot Interface

Pyplot Interface (Quick & convenient)

import matplotlib.pyplot as plt

plt.plot(x, y)
plt.xlabel("X")
plt.ylabel("Y")
plt.show()

Object-Oriented Interface (More control & recommended for complex plots)

fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_xlabel("X")
ax.set_ylabel("Y")
plt.show()

Saving Plots

  • Save as Image: plt.savefig('plot.png')
  • DPI Adjustment: plt.savefig('plot.png', dpi=300)

Matplotlib Functions Cheat Sheet

FunctionPurpose
plt.figure()Create a new figure.
plt.subplots()Create subplots within a figure.
plt.show()Display the current figure.
plt.savefig('filename')Save the figure to a file.
plt.errorbar()Add error bars to data points.

Integrating Matplotlib with Pandas

import pandas as pd
df = pd.DataFrame({'x': range(10), 'y': range(10)})
df.plot(x='x', y='y', kind='line')

Interactive Plots

  • Enable interactivity: %matplotlib notebook or %matplotlib inline (Jupyter)
  • Use plt.pause(0.1) for animations or dynamic updates.

Advanced Features

  • Log Scale: plt.xscale('log'), plt.yscale('log')
  • Twin Axes: ax2 = ax.twinx() for dual y-axes.
  • 3D Plot:
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x, y, z)

Matplotlib and Seaborn Cheat Sheet

Seaborn Integration

  • Histogram: sns.histplot(data)
  • Boxplot: sns.boxplot(x, y)
  • Heatmap: sns.heatmap(data, annot=True)
import seaborn as sns
sns.set(style='whitegrid')  # Set a seaborn style

Matplotlib vs Seaborn Differences

FeatureMatplotlibSeaborn
CustomizationHighMedium
Ease of UseModerateHigh
IntegrationStandalone, supports PandasBuilt on Matplotlib, requires Pandas
Plot TypesBasic and CustomizableAdvanced statistical plots

Tips and Tricks for Effective Visualizations

  • Use contrasting colors for better clarity.
  • Label axes and provide titles for context.
  • Limit the use of 3D plots unless necessary.
  • Avoid overloading the plot with too much data.

Conclusion

Matplotlib remains a cornerstone of data visualization in Python due to its flexibility and depth. By mastering its essential functions and understanding its integration with libraries like Pandas and Seaborn, users can create compelling visualizations for various datasets.

More Cheat Sheets and Top Picks

  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

© 2025 AlmaBetter