⬡ Hub
Skip to content

Matplotlib: Basic Plotting with Pyplot

matplotlib.pyplot is a collection of functions that make Matplotlib work like MATLAB. Each pyplot function makes some change to a figure: e.g., creates a figure, creates a plotting area in a figure, plots some lines in a plotting area, decorates the plot with labels, etc. This is the simplest way to get started with plotting in Matplotlib.

1. Line Plots

Line plots are used to visualize the relationship between two variables, typically showing how one variable changes over another.

import matplotlib.pyplot as plt
import numpy as np

# Simple line plot
x = np.linspace(0, 10, 100) # 100 points between 0 and 10
y = np.sin(x)

plt.plot(x, y)
plt.title('Simple Sine Wave')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.grid(True) # Add a grid
plt.show()

# Plotting multiple lines on the same graph
y2 = np.cos(x)
plt.plot(x, y, label='sin(x)', color='blue', linestyle='--')
plt.plot(x, y2, label='cos(x)', color='red', linestyle='-')
plt.title('Sine and Cosine Waves')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.legend() # Show legend for labels
plt.grid(True)
plt.show()

2. Scatter Plots

Scatter plots display individual data points, showing the relationship between two numerical variables.

import matplotlib.pyplot as plt
import numpy as np

# Generate random data
np.random.seed(42)
x = np.random.rand(50) * 10
y = np.random.rand(50) * 10
colors = np.random.rand(50)
sizes = np.random.rand(50) * 500 # Size of points

plt.scatter(x, y, c=colors, s=sizes, alpha=0.7, cmap='viridis')
plt.title('Random Scatter Plot')
plt.xlabel('X-value')
plt.ylabel('Y-value')
plt.colorbar(label='Color intensity') # Add a color bar
plt.show()

3. Bar Charts

Bar charts are used to compare categorical data, representing each category as a rectangular bar with length proportional to the values they represent.

import matplotlib.pyplot as plt
import numpy as np

categories = ['A', 'B', 'C', 'D', 'E']
values = [23, 45, 56, 12, 39]

plt.bar(categories, values, color='skyblue')
plt.title('Bar Chart Example')
plt.xlabel('Category')
plt.ylabel('Value')
plt.show()

# Horizontal bar chart
plt.barh(categories, values, color='lightcoral')
plt.title('Horizontal Bar Chart Example')
plt.xlabel('Value')
plt.ylabel('Category')
plt.show()

4. Histograms

Histograms display the distribution of a numerical variable, showing the frequency of data points within specified bins.

import matplotlib.pyplot as plt
import numpy as np

# Generate random data (normal distribution)
np.random.seed(42)
data = np.random.randn(1000) # 1000 samples from standard normal distribution

plt.hist(data, bins=30, color='purple', alpha=0.7, edgecolor='black')
plt.title('Histogram of Random Data')
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.grid(axis='y', alpha=0.75)
plt.show()

5. Pie Charts

Pie charts represent proportions of a whole, dividing a circle into sectors that are proportional to the quantity they represent.

import matplotlib.pyplot as plt

labels = ['Apples', 'Bananas', 'Cherries', 'Dates']
sizes = [15, 30, 45, 10]
colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue']
explode = (0, 0.1, 0, 0)  # Explode the 2nd slice (Bananas)

plt.pie(sizes, explode=explode, labels=labels, colors=colors,
        autopct='%1.1f%%', shadow=True, startangle=140)
plt.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.
plt.title('Fruit Distribution')
plt.show()

6. Customizing Plots

Matplotlib provides extensive customization options.

import matplotlib.pyplot as plt
import numpy as np

x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 3, 5, 4, 6])

plt.figure(figsize=(8, 6)) # Set figure size
plt.plot(x, y,
         color='green',          # Line color
         linestyle='-',         # Line style ('-', '--', '-.', ':')
         linewidth=2,            # Line width
         marker='o',             # Marker style ('o', 's', '^', 'D', etc.)
         markersize=8,           # Marker size
         markerfacecolor='red',  # Marker fill color
         markeredgecolor='black',# Marker edge color
         label='My Custom Line')

plt.title('Customized Line Plot', fontsize=16, color='darkblue')
plt.xlabel('X-Label', fontsize=12, color='gray')
plt.ylabel('Y-Label', fontsize=12, color='gray')
plt.xticks(np.arange(0, 6, 1)) # Set x-axis ticks
plt.yticks(np.arange(0, 7, 1)) # Set y-axis ticks
plt.xlim(0.5, 5.5) # Set x-axis limits
plt.ylim(1.5, 6.5) # Set y-axis limits
plt.grid(True, linestyle=':', alpha=0.6) # Customize grid
plt.legend(loc='upper left') # Position legend
plt.text(2, 6, 'Important Point', fontsize=10, color='purple') # Add text
plt.annotate('Peak', xy=(3, 5), xytext=(3.5, 5.5),
             arrowprops=dict(facecolor='black', shrink=0.05),
             fontsize=10, color='black') # Add annotation with arrow
plt.tight_layout() # Adjust layout to prevent labels from overlapping
plt.show()

Further Topics:

  • Object-Oriented Interface (Figure and Axes objects)
  • Subplots and Grids
  • 3D Plotting
  • Animations
  • Working with Text and Annotations
  • Customizing Colormaps and Styles

This document covers the basics of plotting using Matplotlib's pyplot interface, including common plot types and fundamental customization options. These skills are essential for exploratory data analysis and presenting insights visually.