How to Connect Scatterplot Points With Line in Matplotlib?

Matplotlib allows you to create scatter plots and enhance them by connecting points with lines. This technique helps visualize trends and patterns in data more effectively.

Basic Setup

First, import the necessary libraries ?

import matplotlib.pyplot as plt
import numpy as np

Method 1: Using plot() After scatter()

Create a scatter plot first, then add a line connecting the points ?

import matplotlib.pyplot as plt
import numpy as np

# Generate sample data
x = np.array([1, 2, 3, 4, 5, 6])
y = np.array([2, 5, 3, 8, 7, 6])

# Create scatter plot
plt.scatter(x, y, color='blue', s=50)

# Add connecting line
plt.plot(x, y, color='red', linestyle='-', alpha=0.7)

plt.xlabel('X values')
plt.ylabel('Y values')
plt.title('Scatter Plot with Connected Points')
plt.show()

Method 2: Sorting Data for Smooth Lines

When data points are not in order, sort them to create a smooth connecting line ?

import matplotlib.pyplot as plt
import numpy as np

# Generate random data
x = np.random.rand(10) * 10
y = np.random.rand(10) * 10

# Sort data by x values
sorted_indices = np.argsort(x)
x_sorted = x[sorted_indices]
y_sorted = y[sorted_indices]

# Create scatter plot with sorted line
plt.scatter(x, y, color='blue', s=60, label='Data Points')
plt.plot(x_sorted, y_sorted, color='red', linestyle='--', alpha=0.8, label='Trend Line')

plt.xlabel('X values')
plt.ylabel('Y values')
plt.title('Scatter Plot with Sorted Trend Line')
plt.legend()
plt.show()

Method 3: Using Single plot() Function

Create both scatter points and connecting lines in one function call ?

import matplotlib.pyplot as plt
import numpy as np

# Create data points
x = np.linspace(0, 10, 8)
y = np.sin(x) + np.random.normal(0, 0.1, len(x))

# Plot with markers and lines
plt.plot(x, y, 'o-', color='purple', markersize=8, linewidth=2, 
         markerfacecolor='yellow', markeredgecolor='purple')

plt.xlabel('X values')
plt.ylabel('Y values')
plt.title('Combined Scatter and Line Plot')
plt.grid(True, alpha=0.3)
plt.show()

Customization Options

You can customize the appearance of both points and lines ?

import matplotlib.pyplot as plt
import numpy as np

# Sample data
x = np.array([1, 3, 5, 7, 9, 11])
y = np.array([2, 8, 6, 12, 10, 14])

# Customized scatter plot with line
plt.figure(figsize=(10, 6))
plt.scatter(x, y, color='darkblue', s=100, alpha=0.7, edgecolors='black')
plt.plot(x, y, color='orange', linestyle=':', linewidth=3, alpha=0.8)

# Add labels for each point
for i, (xi, yi) in enumerate(zip(x, y)):
    plt.annotate(f'P{i+1}', (xi, yi), xytext=(5, 5), 
                textcoords='offset points', fontsize=10)

plt.xlabel('X Values', fontsize=12)
plt.ylabel('Y Values', fontsize=12)
plt.title('Customized Scatter Plot with Connected Points', fontsize=14)
plt.grid(True, alpha=0.3)
plt.show()

Comparison

Method Use Case Advantages
scatter() + plot() Different styling for points and lines Full control over appearance
Sorted data approach Random or unordered data Creates smooth trend lines
Single plot() with markers Simple, quick visualization Fewer lines of code

Conclusion

Use plt.scatter() followed by plt.plot() for maximum customization. Sort your data when points are unordered to create meaningful trend lines. The single plot() function with markers offers the quickest solution for basic visualizations.

Updated on: 2026-03-27T09:13:51+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements