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

如何将Matplotlib X轴日期格式设为dd/mm/yyyy?解决格式转换报错

Fixing Date Formatting for Pandas Bar Plot X-Axis

Hey there! I see you're running into that frustrating ValueError when trying to reformat the date on your bar plot's X-axis. Let's break down why this is happening and fix it right away.

Why the Error Happens

When you use pandas' plot(kind='bar', x='week'), pandas treats the X-axis as categorical indices (like 0, 1, 2...) instead of actual datetime objects. So when you apply DateFormatter, it tries to interpret those index numbers as dates—which are way before the valid date range (hence the "illegal date" error).

Solution 1: Use Matplotlib's Native bar Function (Preserves Date Axis)

This method keeps the X-axis as proper datetime values, which is great if you need to do more date-based adjustments later:

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime as dt

# First, make sure your 'week' column is datetime type (critical!)
df['week'] = pd.to_datetime(df['week'])

# Filter your data as before
target_week = dt.datetime.strptime('2016-03-13', '%Y-%m-%d')
df_filtered = df[df['week'] == target_week]

# Create a figure and axis manually
fig, ax = plt.subplots()

# Plot with matplotlib's bar, passing the datetime values directly as x
# Replace 'your_numeric_column' with the actual column you're plotting (e.g., sales, count)
ax.bar(df_filtered['week'], df_filtered['your_numeric_column'])

# Set your desired date format
date_formatter = mdates.DateFormatter('%d/%m/%Y')
ax.xaxis.set_major_formatter(date_formatter)

# Rotate labels to prevent overlap (optional but helpful)
plt.xticks(rotation=45)

plt.tight_layout()  # Adjust layout so labels don't get cut off
plt.show()

Solution 2: Quick Fix—Replace X-Tick Labels Directly

If you just need to change the display format without keeping the datetime axis functionality, this is simpler:

import pandas as pd
import matplotlib.pyplot as plt
import datetime as dt

# Ensure 'week' is datetime type
df['week'] = pd.to_datetime(df['week'])

# Filter data
df_w = df['week'] == dt.datetime.strptime('2016-03-13','%Y-%m-%d')
ax = df[df_w].plot(kind='bar', x='week')

# Format the dates from the 'week' column and set them as tick labels
formatted_dates = df[df_w]['week'].dt.strftime('%d/%m/%Y')
ax.set_xticklabels(formatted_dates)

# Rotate labels for readability
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

Key Check

Double-check that your week column is definitely a datetime type—run print(df['week'].dtype) to confirm. If it shows object, use pd.to_datetime() to convert it first, otherwise the date formatting won't work.

内容的提问来源于stack exchange,提问作者RafaBitten

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:47:56