如何在Python中清晰绘制请求时长序列的置信区间
Got it, let's break down how to plot clean, organized confidence intervals for your 6000 request latency measurements in Python. I'll cover two common use cases—static overall confidence intervals and rolling time-series intervals—with actionable code examples you can adapt directly.
First, we'll need a few standard libraries for data handling, stats calculations, and plotting. Install them if you haven't already, then import:
import numpy as np import matplotlib.pyplot as plt from scipy import stats import seaborn as sns # Set a clean plotting style to make outputs look polished sns.set_style("whitegrid")
Replace the simulated data below with your actual 6000-element latency array. I'm mimicking your example's distribution (most values 2-5ms) for demonstration:
# Simulate your latency data (replace this with your real array!) np.random.seed(42) # Ensures reproducibility latency_data = np.random.choice([2,3,4,5], size=6000, p=[0.4, 0.3, 0.2, 0.1]) # For your real data, just use: # latency_data = [3,2,2,3,4,...] # Your full 6000-element list
If you want to show the overall distribution of latencies plus the 95% confidence interval for the mean, this boxplot + error bar combo is clear and concise:
# Calculate mean and 95% confidence interval mean_latency = np.mean(latency_data) confidence_interval = stats.t.interval( confidence=0.95, df=len(latency_data)-1, loc=mean_latency, scale=stats.sem(latency_data) ) # Plot plt.figure(figsize=(8, 5)) # Boxplot shows full data distribution sns.boxplot(x=latency_data, width=0.3, color="#f0f0f0") # Error bar marks mean + 95% CI plt.errorbar( x=0, y=mean_latency, yerr=[[mean_latency - confidence_interval[0]], [confidence_interval[1] - mean_latency]], fmt='o', color='crimson', capsize=8, label=f"Mean ± 95% CI" ) plt.xlabel("Request Latency (ms)") plt.title("Overall Latency Distribution & 95% Confidence Interval") plt.legend() plt.show()
This plot immediately shows where most latencies fall, plus the range where you can be 95% confident the true average latency lies.
If you want to track how latency trends change over the sequence of requests (e.g., how the mean and CI shift across batches of requests), a rolling window approach is perfect. This lets you see if latency stability improves/worsens over time:
def rolling_confidence_interval(data, window_size, confidence=0.95): """Calculate rolling mean and confidence interval for a sliding window""" rolling_mean = [] rolling_ci_lower = [] rolling_ci_upper = [] for i in range(len(data) - window_size + 1): window = data[i:i+window_size] mean = np.mean(window) sem = stats.sem(window) ci = stats.t.interval(confidence, df=window_size-1, loc=mean, scale=sem) rolling_mean.append(mean) rolling_ci_lower.append(ci[0]) rolling_ci_upper.append(ci[1]) return rolling_mean, rolling_ci_lower, rolling_ci_upper # Set window size (adjust based on how granular you want the trend to be) window_size = 100 rolling_mean, rolling_ci_lower, rolling_ci_upper = rolling_confidence_interval(latency_data, window_size) # Plot plt.figure(figsize=(12, 6)) # Optional: Plot raw data (faded to avoid cluttering the trend) plt.plot(latency_data, alpha=0.2, label="Raw Latency Data") # Plot rolling mean line plt.plot( range(window_size-1, len(latency_data)), rolling_mean, color='crimson', linewidth=2, label=f"Rolling Mean (Window Size={window_size})" ) # Fill the confidence interval area plt.fill_between( range(window_size-1, len(latency_data)), rolling_ci_lower, rolling_ci_upper, color='orange', alpha=0.3, label=f"95% Confidence Interval" ) plt.xlabel("Request Index") plt.ylabel("Latency (ms)") plt.title(f"Rolling Latency Trend & 95% Confidence Interval") plt.legend() plt.tight_layout() plt.show()
Adjust the window_size to tweak the smoothness: larger windows show slower, long-term trends; smaller windows highlight short-term fluctuations.
- If the raw data line looks too cluttered (6000 points can get messy), just remove that
plt.plot(latency_data...)line. - Change the confidence level (e.g., 90% or 99%) by modifying the
confidenceparameter in the stats functions. - For interactive plots (great for zooming into specific sections), swap
matplotlibforplotly—the core stats logic stays the same, just the plotting syntax changes.
内容的提问来源于stack exchange,提问作者back2stackoverflow

