Matplotlib绘图报错:x与y维度不匹配问题排查及需求说明
Fix: x and y must have same first dimension Error When Plotting Excel Data
Hey there, let's tackle that annoying dimension mismatch error you're getting. The core issue here is that the x-axis and y-axis data you're feeding into matplotlib don't have the same number of rows. Let's break down what's going wrong in your code and fix it step by step.
What's Broken in Your Current Code
- Index vs. Column Confusion: When you read
data_consumption2withindex_col="Timestamp", you're setting Timestamp as the DataFrame's index. That meansdata_consumption2["Timestamp"]doesn't exist as a regular column anymore—so your line trying to convert it to datetime is either throwing a hidden error or creating a column that doesn't align with your index. - Unapplied Index Change: The line
df_to_plot.set_index(df_to_plot.Timestamp)doesn't actually modifydf_to_plotbecause you didn't assign the result back to the variable. It's a common pandas gotcha! - Vague Column Selection: Using
df_to_plot[df_to_plot.columns[1:]]is risky—you're guessing at the column position instead of explicitly targeting "2053G", which could lead to grabbing the wrong data entirely.
Fixed Code That Works
import pandas as pd import matplotlib.pyplot as plt # Define your time range start_date = "2017-07-24 00:00:00" end_date = "2019-03-09 23:00:00" # Read the Excel sheet properly: parse dates automatically and set index # Note: `sheetname` is deprecated in newer pandas versions, use `sheet_name` instead data_consumption2 = pd.read_excel( r"C:\Users\user\Desktop\Master\Thesis\Tarek\Parent.xlsx", sheet_name="Consumption", index_col="Timestamp", parse_dates=True # This handles datetime conversion for your index automatically ) # Filter data to your desired time window df_to_plot = data_consumption2.loc[start_date:end_date] # Grab the first 720 rows of your target column "2053G" target_column = "2053G" y_values = df_to_plot[target_column].head(720) x_values = y_values.index # Use the datetime index directly for x-axis # Plot the curve plt.figure(figsize=(12, 6)) plt.plot(x_values, y_values, label=target_column) plt.xlabel("Timestamp") plt.ylabel(target_column) plt.title(f"{target_column} Trend (First 720 Rows in Time Range)") plt.legend() plt.xticks(rotation=45) # Rotate x-labels to prevent overlap plt.tight_layout() # Adjust layout so labels don't get cut off plt.show()
Key Fixes Explained
- Automatic Date Parsing: Using
parse_dates=Truewhen reading the Excel file ensures your Timestamp index is properly recognized as datetime objects, no extra conversion needed. - Aligned X/Y Data: By taking
y_values.indexas your x-axis data, you're guaranteed that every y-value has a matching timestamp—so their lengths will always be identical (no more dimension mismatches!). - Explicit Column Targeting: Referencing "2053G" by name eliminates the risk of selecting the wrong column based on position.
Quick Checks If You Still Run Into Issues
- Double-check that the column name in your Excel sheet exactly matches
"2053G"(no typos, extra spaces, or capitalization differences). - Make sure your time range
start_datetoend_dateincludes at least 720 rows—if not,head(720)will just use all available rows, which is fine, but it's good to confirm.
内容的提问来源于stack exchange,提问作者Aghyad Skaif
相关产品推荐
相关产品推荐

