如何在Matplotlib图表X轴正确显示Pandas数据框日期并优化格式?
Solution to Fix Date Sorting & X-Axis Year Display
Here's the corrected code that resolves both your sorting failure and X-axis formatting issues:
import pandas as pd import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter # Read CSV and parse dates with explicit format df = pd.read_csv('your_data.csv', parse_dates=['Date'], date_format='%m/%d/%y') # Sort dataframe by the parsed Date column df_sorted = df.sort_values('Date') # Initialize plot fig, ax = plt.subplots(figsize=(10, 6)) # Plot both response curves using sorted data ax.plot(df_sorted['Date'], df_sorted['% responding right'], label='% Responding Right') ax.plot(df_sorted['Date'], df_sorted['% responding wrong'], label='% Responding Wrong') # Set X-axis to display only the year date_formatter = DateFormatter('%Y') ax.xaxis.set_major_formatter(date_formatter) # Rotate date labels for readability plt.autofmt_xdate() # Add plot labels and legend ax.set_xlabel('Year') ax.set_ylabel('Percentage') ax.set_title('Response Trends Over Time') ax.legend() # Save or display the plot plt.savefig('response_trends.png', dpi=300, bbox_inches='tight') plt.show()
Key Fixes Breakdown:
- Accurate Date Parsing: Using
date_format='%m/%d/%y'ensures pandas correctly interprets yourMM/DD/YYdate format (e.g.,02/08/16becomes2016-02-08), eliminating misinterpretation that caused sorting failures. - Explicit Sorting:
df.sort_values('Date')sorts the data chronologically, and using this sorted dataframe for plotting fixes the Y-value order chaos. - Year-Only X-Axis:
DateFormatter('%Y')overrides the default full-date display to show only the 4-digit year. - Controlled Axes Setup: Using
fig, ax = plt.subplots()gives direct control over axis formatting, avoiding implicit plotting pitfalls.
Common Pitfalls to Skip:
- Never skip specifying
date_formatduring date parsing—pandas may guess the wrong order (DD/MM vs MM/DD) and break sorting. - Always plot the sorted dataframe, not the original unsorted one.
- Don’t rely on default date formatting if you need a specific display (like year-only).
内容的提问来源于stack exchange,提问作者Yes
相关产品推荐
相关产品推荐

