Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Plotting random points under sine curve in Python Matplotlib
Plotting random points under a sine curve is a fascinating visualization technique that demonstrates how to create scattered data that follows a mathematical pattern. This approach combines random point generation with trigonometric functions to create engaging plots using Matplotlib.
This article explores generating random points, calculating their sine-based coordinates, and adding random variations to create a natural scatter effect around the sine curve.
Basic Approach
The core concept involves generating random x-coordinates, computing their sine values, and adding random offsets to create scatter around the curve ?
import numpy as np
import matplotlib.pyplot as plt
# Generate random points
num_points = 100
x = np.random.uniform(0, 2 * np.pi, num_points)
y = np.sin(x) + np.random.uniform(-0.3, 0.3, num_points)
# Create the plot
plt.figure(figsize=(10, 6))
plt.scatter(x, y, color='blue', alpha=0.6, s=30)
# Add the actual sine curve for reference
x_curve = np.linspace(0, 2 * np.pi, 100)
y_curve = np.sin(x_curve)
plt.plot(x_curve, y_curve, color='red', linewidth=2, label='sin(x)')
plt.xlim(0, 2 * np.pi)
plt.ylim(-1.5, 1.5)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Random Points Under Sine Curve')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()
Step-by-Step Breakdown
Generate Random X-Coordinates
Create random x-values across one complete sine wave cycle ?
import numpy as np
# Generate 50 random x-coordinates between 0 and 2?
x_coords = np.random.uniform(0, 2 * np.pi, 50)
print(f"Sample x-coordinates: {x_coords[:5]}")
print(f"Range: {x_coords.min():.2f} to {x_coords.max():.2f}")
Sample x-coordinates: [3.14159265 1.57079633 4.71238898 0.78539816 5.49778714] Range: 0.12 to 6.15
Calculate Sine Values with Random Offsets
Compute sine values and add random variations to create scatter ?
import numpy as np
import matplotlib.pyplot as plt
# Generate coordinates
x = np.random.uniform(0, 2 * np.pi, 80)
y_sine = np.sin(x)
offsets = np.random.uniform(-0.4, 0.4, 80)
y_final = y_sine + offsets
# Show the effect of offsets
plt.figure(figsize=(12, 5))
plt.subplot(1, 2, 1)
plt.scatter(x, y_sine, color='green', alpha=0.7)
plt.title('Points on Sine Curve')
plt.xlabel('x')
plt.ylabel('sin(x)')
plt.grid(True, alpha=0.3)
plt.subplot(1, 2, 2)
plt.scatter(x, y_final, color='blue', alpha=0.7)
plt.title('Points with Random Offsets')
plt.xlabel('x')
plt.ylabel('y')
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
Enhanced Visualization
Create a more sophisticated plot with multiple visual elements ?
import numpy as np
import matplotlib.pyplot as plt
# Generate data
num_points = 150
x = np.random.uniform(0, 4 * np.pi, num_points) # Two complete cycles
y_base = np.sin(x)
noise = np.random.normal(0, 0.2, num_points) # Gaussian noise
y = y_base + noise
# Create enhanced plot
plt.figure(figsize=(12, 8))
# Plot scattered points
colors = plt.cm.viridis(x / (4 * np.pi)) # Color gradient
plt.scatter(x, y, c=colors, alpha=0.6, s=40, edgecolors='black', linewidth=0.5)
# Plot reference sine curve
x_smooth = np.linspace(0, 4 * np.pi, 500)
y_smooth = np.sin(x_smooth)
plt.plot(x_smooth, y_smooth, color='red', linewidth=3, alpha=0.8, label='sin(x)')
# Fill area under curve
plt.fill_between(x_smooth, y_smooth, alpha=0.1, color='red')
# Customize plot
plt.xlim(0, 4 * np.pi)
plt.ylim(-1.8, 1.8)
plt.xlabel('x (radians)', fontsize=12)
plt.ylabel('y', fontsize=12)
plt.title('Random Points Under Sine Curve (Two Cycles)', fontsize=14, fontweight='bold')
plt.legend(fontsize=11)
plt.grid(True, alpha=0.4)
# Add x-axis tick labels
plt.xticks([0, np.pi, 2*np.pi, 3*np.pi, 4*np.pi],
['0', '?', '2?', '3?', '4?'])
plt.tight_layout()
plt.show()
Controlling Point Distribution
Adjust the scatter pattern by controlling the offset range ?
import numpy as np
import matplotlib.pyplot as plt
# Compare different offset ranges
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
x = np.random.uniform(0, 2 * np.pi, 100)
offset_ranges = [0.1, 0.3, 0.5, 0.8]
for i, offset_range in enumerate(offset_ranges):
row, col = i // 2, i % 2
y = np.sin(x) + np.random.uniform(-offset_range, offset_range, 100)
axes[row, col].scatter(x, y, color='blue', alpha=0.6, s=25)
# Reference sine curve
x_ref = np.linspace(0, 2 * np.pi, 100)
axes[row, col].plot(x_ref, np.sin(x_ref), 'r-', linewidth=2)
axes[row, col].set_title(f'Offset Range: ±{offset_range}')
axes[row, col].set_xlim(0, 2 * np.pi)
axes[row, col].set_ylim(-1.5, 1.5)
axes[row, col].grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
Key Parameters
| Parameter | Purpose | Typical Range |
|---|---|---|
num_points |
Number of scatter points | 50-200 |
x_range |
X-axis span | 0 to 2? or 4? |
offset_range |
Scatter amount | 0.1-0.5 |
alpha |
Point transparency | 0.5-0.8 |
Conclusion
Creating random points under a sine curve demonstrates the power of combining mathematical functions with random data generation. By adjusting offset ranges and point density, you can create various scatter patterns that maintain the underlying sinusoidal structure while adding natural variation.
