Matplotlib Plotting Multiple Lines in 3D

When I started working with 3D data visualization in Python, I found plotting multiple lines in three dimensions a bit tricky. Matplotlib’s 3D plotting capabilities are powerful but can be intimidating without an easy guide. I’ve experimented with several approaches, and I want to share the ones that worked best for me.

Whether you’re analyzing geographical data, financial trends over time, or any multi-dimensional dataset typical in the USA, plotting multiple lines in 3D can give you deeper insights. In this tutorial, I’ll walk you through simple and effective methods to do this using Matplotlib.

Let’s get in!

Get Started with 3D Plotting in Matplotlib

Before diving into multiple lines, let’s quickly set up the environment. You’ll need Matplotlib installed:

pip install matplotlib

Matplotlib’s 3D plotting is part of the mpl_toolkits.mplot3d module, which you import alongside the usual matplotlib.pyplot.

Method 1: Plot Multiple Lines Using a Loop

The simple way I use to plot multiple 3D lines is by looping through datasets in Python. This method is flexible and great when you have several series to plot.

Here’s a practical example: Imagine you’re visualizing the monthly sales trends for three different retail stores across the USA over a year. Each store’s sales data is a line in 3D space, where the x-axis is the month, the y-axis is the store ID, and the z-axis is the sales amount.

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

# Sample data: Months (1 to 12)
months = np.arange(1, 13)

# Sales data for three stores (randomly generated for example)
store_sales = {
    'Store A': np.random.randint(2000, 5000, size=12),
    'Store B': np.random.randint(1500, 4500, size=12),
    'Store C': np.random.randint(3000, 6000, size=12)
}

fig = plt.figure(figsize=(10, 7))
ax = fig.add_subplot(111, projection='3d')

# Assign a unique y-value for each store for separation
store_ids = {'Store A': 1, 'Store B': 2, 'Store C': 3}

for store, sales in store_sales.items():
    y = np.full_like(months, store_ids[store])  # constant y for each store
    ax.plot(months, y, sales, label=store)

ax.set_xlabel('Month')
ax.set_ylabel('Store ID')
ax.set_zlabel('Sales ($)')
ax.set_yticks(list(store_ids.values()))
ax.set_yticklabels(list(store_ids.keys()))
ax.set_title('Monthly Sales Trends for USA Retail Stores')
ax.legend()

plt.show()

You can refer to the screenshot below to see the output.

Matplotlib Plot Multiple Lines in 3D

In this example, I used a loop to plot each store’s sales as a separate line in 3D. This approach is clean and easy to scale if you have more stores or datasets.

Read Draw a Vertical Line Matplotlib

Method 2: Plot Multiple Lines by Predefining Arrays

Sometimes, you might have your data organized in arrays or matrices. You can plot multiple lines by iterating over these arrays.

Let’s say you’re analyzing temperature variations across three major US cities over 12 months. Here’s how you can plot these lines:

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

# Months
months = np.arange(1, 13)

# Temperature data for New York, Los Angeles, Chicago (in Fahrenheit)
temps = np.array([
    [31, 35, 42, 55, 65, 75, 80, 78, 70, 58, 47, 35],  # New York
    [58, 60, 62, 65, 68, 73, 78, 79, 76, 68, 61, 55],  # Los Angeles
    [25, 30, 40, 55, 65, 75, 80, 78, 68, 55, 40, 30]   # Chicago
])

cities = ['New York', 'Los Angeles', 'Chicago']

fig = plt.figure(figsize=(10, 7))
ax = fig.add_subplot(111, projection='3d')

for i, city in enumerate(cities):
    y = np.full_like(months, i + 1)  # y-axis is city index
    ax.plot(months, y, temps[i], label=city)

ax.set_xlabel('Month')
ax.set_ylabel('City')
ax.set_yticks(range(1, len(cities) + 1))
ax.set_yticklabels(cities)
ax.set_zlabel('Avg Temperature (°F)')
ax.set_title('Monthly Average Temperatures in Major US Cities')
ax.legend()

plt.show()

You can refer to the screenshot below to see the output.

Matplotlib 3D Plotting Multiple Lines in

This method is handy when your data is already in matrix form. The key is to keep the y-axis as a constant per line to separate the lines in 3D space.

Method 3: Customize Lines with Colors and Markers

To make your 3D plots more readable and visually appealing, I always customize colors and markers for each line. This is especially useful when you have many lines.

Here’s an enhanced version of the previous example with colors and markers:

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

months = np.arange(1, 13)
temps = np.array([
    [31, 35, 42, 55, 65, 75, 80, 78, 70, 58, 47, 35],
    [58, 60, 62, 65, 68, 73, 78, 79, 76, 68, 61, 55],
    [25, 30, 40, 55, 65, 75, 80, 78, 68, 55, 40, 30]
])

cities = ['New York', 'Los Angeles', 'Chicago']
colors = ['r', 'g', 'b']
markers = ['o', '^', 's']

fig = plt.figure(figsize=(10, 7))
ax = fig.add_subplot(111, projection='3d')

for i, city in enumerate(cities):
    y = np.full_like(months, i + 1)
    ax.plot(months, y, temps[i], label=city, color=colors[i], marker=markers[i])

ax.set_xlabel('Month')
ax.set_ylabel('City')
ax.set_yticks(range(1, len(cities) + 1))
ax.set_yticklabels(cities)
ax.set_zlabel('Avg Temperature (°F)')
ax.set_title('Monthly Average Temperatures in Major US Cities with Custom Colors')
ax.legend()

plt.show()

You can refer to the screenshot below to see the output.

Matplotlib 3D Plot Multiple Lines in

Adding colors and markers makes it easier to distinguish lines, especially when presenting to stakeholders or in reports.

Plotting multiple lines in 3D with Matplotlib is a skill I use often for complex data visualization projects. Whether you’re tracking sales trends across US stores or comparing climate data across cities, these methods help you visualize your data in three dimensions.

The key is to keep your data organized and use loops or array iterations to plot each line distinctly. Don’t forget to customize your plot with labels, legends, and colors to make your visualization professional and insightful.

If you’re working on US-specific datasets, these approaches will help you create meaningful 3D line plots that can reveal trends and patterns not obvious in 2D charts.

You may also read other Matplotlib articles:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.