同一坐标轴绘制两个散点图时Matplotlib输出异常求助
draw Function Hey there! Let's work through why your draw function is acting up with your specific dataset, even when the other two functions run smoothly and your data shape checks out. Since manual test inputs work fine, the issue is almost certainly a subtle, easy-to-miss quirk in your actual data. Here are actionable steps to diagnose and fix this:
Common Culprits & Fixes
Hidden invalid values: Even if your data is numeric,
NaN,inf, or-infvalues can break plotting functions without obvious errors. Run these checks in your Jupyter notebook to rule this out:import numpy as np # Check X_test for invalid values print("NaN in X_test:", np.isnan(X_test).any()) print("Inf/-Inf in X_test:", np.isinf(X_test).any()) # Check y_test print("NaN in y_test:", np.isnan(y_test).any()) print("Inf/-Inf in y_test:", np.isinf(y_test).any())If you find any, clean the data with
X_test = np.nan_to_num(X_test)or remove rows with invalid entries.Extreme value outliers: A single outlier can skew plot axes so much that the rest of your data becomes invisible. Compare the value ranges of your actual data to your manual test data:
print("X_test range:", (X_test.min(), X_test.max())) print("y_test range:", (y_test.min(), y_test.max()))If there's a massive discrepancy, try filtering out outliers or adjusting the plot's axis limits manually in your
drawfunction.Unexpected data types: Even if your data is numeric, it might be stored as an
objectdtype (from a messy conversion) or a type the plotting library doesn't handle well. Verify the dtypes:print("X_test dtype:", X_test.dtype) print("y_test dtype:", y_test.dtype)If they're
object, convert them to a proper numeric type:X_test = X_test.astype(np.float64) y_test = y_test.astype(np.float64)Dimension mismatch (even if shape looks right): Sometimes a 2D array (e.g.,
(n_samples, 1)) can cause issues if thedrawfunction expects a 1D array (e.g.,(n_samples,)). Check the dimensions with:print("X_test shape:", X_test.shape) print("y_test shape:", y_test.shape)If you see an extra dimension, flatten it with
X_test = X_test.ravel()orX_test = X_test.squeeze().Isolate problematic data: Try passing a small subset of your data (e.g., the first 10 rows) to
draw. If it works, use binary search to find the exact row that's causing the failure—this can reveal edge cases you didn't anticipate.
Bonus Tip
If you're getting an error traceback in Jupyter, share the full stack trace (even if it seems cryptic)! The line where the error occurs will often point directly to the root cause (e.g., a matplotlib error about incompatible array shapes).
内容的提问来源于stack exchange,提问作者Jay Vee

