You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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 your MM/DD/YY date format (e.g., 02/08/16 becomes 2016-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_format during 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 00:25:09