代码无报错却生成空图,多店铺销售额折线图问题如何解决?
Hey there! No error messages but an empty plot? Super frustrating, right? Let’s walk through the most likely reasons and how to get those lines showing up.
Common Causes & Fixes
1. Your Sales Data Has Missing/Zero Values
If your a, b, c, d columns are full of NaN values or all zeros, Matplotlib won’t draw any visible lines.
How to check:
Run these commands to inspect your data:
# Check for missing values print(df[['a', 'b', 'c', 'd']].isnull().sum()) # Check if all values are zero print((df[['a', 'b', 'c', 'd']] == 0).all())
Fix:
- Clean your data: Fill missing values with a reasonable number (like the mean of the column) using
df[['a','b','c','d']] = df[['a','b','c','d']].fillna(df.mean()) - If zeros are intentional, confirm your axis range includes zero (Matplotlib usually handles this automatically, but it’s worth verifying)
2. Date Axis & Data Aren’t Properly Aligned
Even if you have a date column, if it’s formatted incorrectly (like a string instead of datetime) or you’re not plotting against it properly, lines might get drawn outside the visible plot area.
How to check:
Verify your date column is a datetime type:
print(df['date'].dtype)
If it shows object, it’s a string, not a datetime.
Fix:
Convert the date column to datetime first:
df['date'] = pd.to_datetime(df['date'])
Then explicitly pass the date column as your x-axis when plotting:
import matplotlib.pyplot as plt plt.figure(figsize=(12,6)) plt.plot(df['date'], df['a'], label='Store A') plt.plot(df['date'], df['b'], label='Store B') plt.plot(df['date'], df['c'], label='Store C') plt.plot(df['date'], df['d'], label='Store D') plt.xlabel('Date') plt.ylabel('Sales') plt.title('Daily Sales by Store') plt.legend() plt.xticks(rotation=45) plt.tight_layout() plt.show()
3. Your Data Values Are Way Outside the Default Axis Range
If your sales numbers are extremely large or tiny, Matplotlib’s auto-scaling might fail (though rare), or you might have accidentally set a fixed axis range that excludes your data.
How to check:
Print the min and max of your sales columns to confirm:
print(df[['a', 'b', 'c', 'd']].describe())
Fix:
Force auto-scaling for both axes:
plt.autoscale(enable=True, axis='both', tight=True)
Or manually set the y-axis range to cover your data:
plt.ylim(df[['a','b','c','d']].min().min() - 100, df[['a','b','c','d']].max().max() + 100)
4. You’re Plotting the Wrong Data (Or Forgetting to Show the Plot)
It sounds silly, but it happens! Double-check that you’re referencing the correct column names (no typos) and that you’re calling plt.show() at the end of your code (required for non-Jupyter environments).
Fix:
- Confirm column names match exactly:
print(df.columns) - Add
plt.show()after your plotting commands to render the chart
Full Working Example
Here’s a complete code snippet to generate test data and plot it, so you can compare with your code:
import pandas as pd import matplotlib.pyplot as plt import numpy as np # Create sample 31-day DataFrame dates = pd.date_range(start='2024-01-01', periods=31) # Generate random sales data sales_data = pd.DataFrame({ 'date': dates, 'a': np.random.randint(1000, 5000, size=31), 'b': np.random.randint(800, 4500, size=31), 'c': np.random.randint(1200, 5500, size=31), 'd': np.random.randint(900, 4800, size=31) }) # Plot the lines plt.figure(figsize=(12,6)) plt.plot(sales_data['date'], sales_data['a'], label='Store A', linewidth=2) plt.plot(sales_data['date'], sales_data['b'], label='Store B', linewidth=2) plt.plot(sales_data['date'], sales_data['c'], label='Store C', linewidth=2) plt.plot(sales_data['date'], sales_data['d'], label='Store D', linewidth=2) # Customize the plot plt.xlabel('Date', fontsize=12) plt.ylabel('Sales Amount', fontsize=12) plt.title('Daily Sales for 4 Store Types', fontsize=14, pad=20) plt.legend(fontsize=10) plt.xticks(rotation=45) plt.tight_layout() plt.show()
内容的提问来源于stack exchange,提问作者user8810618

