⬡ Hub
Skip to content

Matplotlib: Static, Animated, and Interactive Visualizations

Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. It provides an object-oriented API for embedding plots into applications using general-purpose GUI toolkits like Tkinter, wxPython, Qt, or GTK+. It is also a popular choice for generating plots, histograms, power spectra, bar charts, errorcharts, scatterplots, etc., with a few lines of code.

Key Features:

  • Versatile Plotting: Capable of generating various types of plots with high-quality output in many formats.
  • Customization: Extensive control over every aspect of a figure, including figure size, resolution, line styles, font properties, and axis properties.
  • Integration: Designed to work well with NumPy arrays and Pandas DataFrames.
  • Multiple Backends: Supports different backends for rendering (e.g., interactive GUI backends, non-interactive hardcopy backends).

Getting Started: Installation

You can install Matplotlib using pip or conda.

Using pip:

pip install matplotlib

Using conda:

conda install matplotlib

Basic Concepts: Figures and Axes

In Matplotlib, the plotting hierarchy consists of a Figure object, which is the overall window or page, and one or more Axes objects, which are the individual plots on the figure.

Simple Plot

import matplotlib.pyplot as plt
import numpy as np

# Data for plotting
x = np.linspace(0, 10, 100)
y = np.sin(x)

# Create a figure and an axes
fig, ax = plt.subplots()

# Plot the data
ax.plot(x, y)

# Add labels and title
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_title('Simple Sine Wave Plot')

# Display the plot
plt.show()

Multiple Plots on One Figure (Subplots)

import matplotlib.pyplot as plt
import numpy as np

# Data for plotting
x = np.linspace(0, 2 * np.pi, 400)
y_sin = np.sin(x)
y_cos = np.cos(x)

# Create a figure with two subplots (1 row, 2 columns)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))

# Plot on the first subplot
ax1.plot(x, y_sin, color='blue')
ax1.set_title('Sine Wave')
ax1.set_xlabel('Angle (radians)')
ax1.set_ylabel('Amplitude')

# Plot on the second subplot
ax2.plot(x, y_cos, color='red')
ax2.set_title('Cosine Wave')
ax2.set_xlabel('Angle (radians)')
ax2.set_ylabel('Amplitude')

# Adjust layout to prevent overlapping
plt.tight_layout()

# Display the plot
plt.show()

Other Common Plot Types

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

# Bar Chart
fig, ax = plt.subplots()
categories = ['A', 'B', 'C', 'D']
values = [23, 45, 56, 12]
ax.bar(categories, values, color='skyblue')
ax.set_title('Bar Chart Example')
plt.show()

# Scatter Plot
fig, ax = plt.subplots()
np.random.seed(42)
x_scatter = np.random.rand(50) * 10
y_scatter = np.random.rand(50) * 10
ax.scatter(x_scatter, y_scatter, color='green', alpha=0.7)
ax.set_title('Scatter Plot Example')
plt.show()

# Histogram
fig, ax = plt.subplots()
data_hist = np.random.randn(1000)
ax.hist(data_hist, bins=30, color='purple', alpha=0.7)
ax.set_title('Histogram Example')
plt.show()

Further Topics:

  • Customizing Plots (colors, markers, line styles)
  • Adding Text, Annotations, and Legends
  • Working with Images
  • 3D Plotting
  • Animations
  • Integrating with Pandas and Seaborn

This document provides a basic introduction to Matplotlib. More detailed topics, advanced customization, and practical examples will be covered in subsequent files.