Complete Guide to Multiple Line Plotting in Python Using Matplotlib

Nov 21, 2025 · Programming · 7 views · 7.8

Keywords: Python | Matplotlib | Data Visualization | Multiple Line Plots | Subplots

Abstract: This article provides a comprehensive guide to creating multiple line plots in Python using the Matplotlib library. It analyzes common beginner mistakes, explains the proper usage of plt.plot() function including line style settings, legend addition, and axis control. Combined with subplots functionality, it demonstrates advanced techniques for creating multi-panel figures, helping readers master core concepts and practical methods in data visualization.

Problem Analysis and Common Mistakes

In data visualization, beginners often encounter issues when trying to plot multiple lines in the same figure. In the original code, calling plt.show() within each loop iteration causes separate figure windows to be generated and displayed. The correct approach is to call plt.show() only after completing all plotting operations.

Basic Multiple Line Plotting Method

The core technique for plotting multiple lines in Matplotlib involves multiple calls to the plt.plot() function. Each plt.plot() call adds a new curve to the current figure. Here's a standard example:

import matplotlib.pyplot as plt

# Prepare data
x_values_1 = [1, 2, 3, 4, 5]
y_values_1 = [2, 4, 6, 8, 10]
x_values_2 = [1, 2, 3, 4, 5]
y_values_2 = [1, 3, 5, 7, 9]

# Plot multiple lines
plt.plot(x_values_1, y_values_1, 'b-', label='Blue Line')
plt.plot(x_values_2, y_values_2, 'r--', label='Red Dashed Line')

# Add legend and labels
plt.legend(loc='best')
plt.xlabel('X-axis Label')
plt.ylabel('Y-axis Label')
plt.title('Multiple Line Plot Example')

# Display the figure
plt.show()

Line Style and Color Configuration

In the plt.plot() function, the third parameter specifies line style and color. Color codes include: 'b' (blue), 'r' (red), 'g' (green), etc. Line styles include: '-' (solid), '--' (dashed), '-.' (dash-dot), etc. When combined, such as 'b-', it represents a blue solid line.

Legend Functionality Details

Legends are essential for distinguishing between different lines. By setting the label parameter in each plt.plot() call and then invoking plt.legend(), Matplotlib automatically generates a legend. The loc='best' parameter allows Matplotlib to choose the optimal legend position, avoiding data occlusion.

Creating Multiple Subplots with subplots

For more complex visualization requirements, the plt.subplots() function creates figures containing multiple subplots. This method offers better layout control and flexibility:

import matplotlib.pyplot as plt
import numpy as np

# Create a 2x2 subplot grid
fig, axs = plt.subplots(2, 2, figsize=(10, 8))

# Generate sample data
x = np.linspace(0, 10, 100)

# Plot different functions in each subplot
axs[0, 0].plot(x, np.sin(x), 'b-')
axs[0, 0].set_title('Sine Function')

axs[0, 1].plot(x, np.cos(x), 'r--')
axs[0, 1].set_title('Cosine Function')

axs[1, 0].plot(x, np.tan(x), 'g-.')
axs[1, 0].set_title('Tangent Function')

axs[1, 1].plot(x, np.exp(x), 'm:')
axs[1, 1].set_title('Exponential Function')

# Add common labels to all subplots
for ax in axs.flat:
    ax.set(xlabel='x values', ylabel='y values')

# Automatically hide overlapping labels
for ax in axs.flat:
    ax.label_outer()

plt.tight_layout()
plt.show()

Axis Control and Customization

Matplotlib provides extensive axis control capabilities. After obtaining the current axis object via plt.gca(), various customizations can be applied:

import matplotlib.pyplot as plt

# Plot basic graph
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])

# Get axis object and apply customizations
ax = plt.gca()
ax.invert_xaxis()  # Invert x-axis
ax.yaxis.tick_right()  # Move y-axis ticks to right
ax.yaxis.set_label_position("right")  # Move y-axis label to right

plt.show()

Practical Application Example

Suppose we need to visualize multiple time series data, here's a complete example:

import matplotlib.pyplot as plt
import numpy as np

# Simulate multiple time series data
time_points = np.arange(0, 100, 1)
dataset_1 = np.sin(time_points * 0.1) + np.random.normal(0, 0.1, 100)
dataset_2 = np.cos(time_points * 0.1) + np.random.normal(0, 0.1, 100)
dataset_3 = np.sin(time_points * 0.2) + np.random.normal(0, 0.1, 100)

# Create figure and axes
fig, ax = plt.subplots(figsize=(12, 6))

# Plot all time series
ax.plot(time_points, dataset_1, 'b-', label='Dataset 1', linewidth=2)
ax.plot(time_points, dataset_2, 'r--', label='Dataset 2', linewidth=2)
ax.plot(time_points, dataset_3, 'g-.', label='Dataset 3', linewidth=2)

# Complete figure setup
ax.set_xlabel('Time Points')
ax.set_ylabel('Values')
ax.set_title('Multiple Time Series Comparison')
ax.legend(loc='upper right')
ax.grid(True, alpha=0.3)

# Display the figure
plt.tight_layout()
plt.show()

Best Practices and Considerations

1. Avoid calling plt.show() within loops, as this generates multiple separate figures

2. Use the label parameter to describe each line and display legends via plt.legend()

3. For large datasets, consider using subplots to prevent overcrowded figures

4. Set appropriate line styles and colors to ensure good readability

5. Use plt.tight_layout() to automatically adjust subplot spacing and prevent label overlap

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.