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
Selected Reading
How to plot a line in Matplotlib with an interval at each data point?
To plot a line in Matplotlib with confidence intervals or error bars at each data point, we can use the fill_between() method to create a shaded region around the main line. This technique is commonly used to show uncertainty or variability in data visualization.
Basic Setup
First, let's understand the key steps involved ?
- Create arrays for means and standard deviations
- Plot the main line using
plot()method - Use
fill_between()to create shaded intervals - Customize appearance with colors and transparency
Example
Here's how to create a line plot with confidence intervals ?
import numpy as np
import matplotlib.pyplot as plt
# Set figure size
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Data points
means = np.array([3, 5, 1, 8, 4, 6])
stds = np.array([1.3, 2.6, 0.78, 3.01, 2.32, 2.9])
# Plot the main line
plt.plot(means, color='red', linewidth=2, label='Mean values')
# Fill the confidence interval
plt.fill_between(range(len(means)), means - stds, means + stds,
alpha=0.3, color='yellow', label='±1 Standard Deviation')
plt.xlabel('Data Points')
plt.ylabel('Values')
plt.title('Line Plot with Confidence Intervals')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()
Advanced Example with Custom Intervals
You can also create asymmetric intervals or use different confidence levels ?
import numpy as np
import matplotlib.pyplot as plt
# Generate sample data
x = np.linspace(0, 10, 20)
y = np.sin(x) + 0.5 * np.random.randn(20)
error = 0.3 + 0.1 * np.random.randn(20)
plt.figure(figsize=(10, 6))
# Plot main line
plt.plot(x, y, 'o-', color='blue', linewidth=2, markersize=6, label='Data')
# Add confidence intervals
plt.fill_between(x, y - error, y + error, alpha=0.2, color='blue',
label='Confidence Interval')
plt.xlabel('X values')
plt.ylabel('Y values')
plt.title('Line Plot with Variable Confidence Intervals')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()
Key Parameters
| Parameter | Purpose | Example Values |
|---|---|---|
alpha |
Controls transparency | 0.2 to 0.7 |
color |
Sets fill color | 'yellow', 'blue', '#FF5733' |
linewidth |
Main line thickness | 1 to 5 |
Conclusion
Use fill_between() to create confidence intervals around line plots. Adjust alpha for transparency and choose appropriate colors to make the intervals visually clear without overwhelming the main data line.
Advertisements
