How can matplotlib be used to plot 3 different datasets on a single graph in Python?

Matplotlib is a popular Python package used for data visualization. It helps understand data patterns without performing complicated computations and effectively communicates quantitative insights to the audience.

Matplotlib creates 2D plots and comes with an object-oriented API for embedding plots in Python applications. It works with IPython shells, Jupyter notebooks, and Spyder IDE, and is built using NumPy.

Installation

Install Matplotlib using pip ?

pip install matplotlib

Plotting Multiple Datasets on a Single Graph

You can plot multiple datasets on a single graph by calling plot() multiple times with different data and labels. Here's how to plot three different mathematical functions ?

import matplotlib.pyplot as plt
import numpy as np

# Create data
x = np.linspace(0, 2, 100)

# Create figure and axis
fig, ax = plt.subplots()

# Plot three different datasets
ax.plot(x, x, label='linear')
ax.plot(x, x**2, label='quadratic') 
ax.plot(x, x**3, label='cubic')

# Add labels and title
ax.set_xlabel('x values')
ax.set_ylabel('y values')
ax.set_title('Three Mathematical Functions')

# Show legend
ax.legend()

# Display plot
plt.show()

Output

x values y values Three Mathematical Functions linear quadratic cubic 0.0 0.5 1.0 1.5 2.0 0 2 4 6 8

Key Components Explained

  • Multiple plot() calls ? Each dataset is plotted separately with its own label
  • Labels ? The label parameter identifies each dataset in the legend
  • Legend ? ax.legend() displays the legend showing which line represents which dataset
  • Axis labels ? set_xlabel() and set_ylabel() label the axes
  • Title ? set_title() adds a descriptive title to the plot

Plotting Different Types of Data

You can also plot completely different datasets, such as experimental data or time series ?

import matplotlib.pyplot as plt
import numpy as np

# Create different datasets
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May']
sales_2022 = [120, 140, 110, 160, 180]
sales_2023 = [130, 150, 125, 170, 195]
target = [125, 135, 130, 165, 185]

# Create the plot
plt.figure(figsize=(10, 6))
plt.plot(months, sales_2022, marker='o', label='2022 Sales')
plt.plot(months, sales_2023, marker='s', label='2023 Sales')  
plt.plot(months, target, marker='^', linestyle='--', label='Target')

plt.xlabel('Months')
plt.ylabel('Sales (in thousands)')
plt.title('Sales Comparison Across Months')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()

Conclusion

Matplotlib allows you to plot multiple datasets on a single graph by calling plot() multiple times with different data and labels. Use legend() to distinguish between datasets and ensure proper axis labels for clarity.

Updated on: 2026-03-25T14:50:49+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements