如何在Python代码中集成plt.subplots批量绘制子图?
Plotting All Outlier Windows with
plt.subplots Hey there! No worries at all—we all start somewhere with Python and data visualization. Let's tweak your code to use plt.subplots so you can plot every outlier's window in one go. Here's how to do it step by step:
Key Idea
Instead of manually picking a single num to plot, we'll:
- Count how many outliers we have
- Create a grid of subplots matching that number
- Loop through each outlier, plot its window on a separate subplot
Modified Full Code
import pandas as pd import numpy as np from scipy import stats import matplotlib.pyplot as plt # Load your data (same as before) df = pd.read_csv(r"/Users/aaronhuang/Desktop/ffp/exfileCLEAN2.csv", skiprows=[1]) magnitudes = df['Magnitude '].values times = df['Time '].values # Calculate outliers (same as before) zscores = np.abs(stats.zscore(magnitudes, ddof=1)) outlier_indicies = np.argwhere(zscores > 3).flatten() n_outliers = len(outlier_indicies) # Exit early if no outliers are found (avoids errors) if n_outliers == 0: print("No outliers detected!") else: # Set up subplots: adjust rows/cols based on number of outliers # Here we use 2 columns, rows are calculated automatically fig, axes = plt.subplots(nrows=(n_outliers + 1) // 2, ncols=2, figsize=(14, 6 * ((n_outliers + 1) // 2))) # Flatten axes into a 1D array to make looping easier (works even for 1 row) axes = axes.flatten() window = 2 # Your original window size # Loop through each outlier and plot its window for i, idx in enumerate(outlier_indicies): # Get the time and magnitude slice for this outlier's window x = times[idx - window : idx + window + 1] y = magnitudes[idx - window : idx + window + 1] # Plot on the i-th subplot axes[i].plot(x, y, marker='o', label=f'Outlier at index {idx}') axes[i].set_xlabel('Time (units)') axes[i].set_ylabel('Magnitude (units)') axes[i].set_title(f'Outlier #{i+1} (Time: {times[idx]:.2f})') axes[i].legend() axes[i].grid(True) # Optional: adds grid for readability # Hide any empty subplots (if number of outliers is odd) for j in range(i + 1, len(axes)): axes[j].axis('off') # Adjust layout so plots don't overlap plt.tight_layout() plt.show()
What Changed?
- We added
n_outliers = len(outlier_indicies)to know how many subplots we need plt.subplots()creates a grid of plots: we use 2 columns, and calculate rows based on the number of outliersaxes.flatten()turns the 2D axes array into a 1D list, making it easy to loop through each plot- The
forloop goes through every outlier index, plots its window on the corresponding subplot - We added titles, legends, and grid lines to make each subplot clearer
plt.tight_layout()ensures labels/titles don't overlap between subplots- We handle the case where there are no outliers to avoid errors
Feel free to adjust the figsize or number of columns (change ncols=2 to ncols=3 if you want more plots per row) to fit your needs!
内容的提问来源于stack exchange,提问作者Aaron Huang
相关产品推荐
相关产品推荐

