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

X轴日期刻度未按时间间隔正确分隔问题排查与解决

问题描述

现有如下数据:

Date  Chemical
10 2021-11-20        21
11 2021-11-26        19
12 2021-11-26        31
13 2021-11-26        32
14 2021-11-27        31
0  2021-12-06        21
6  2021-12-16        23
7  2021-12-16        24
8  2021-12-16        23
9  2021-12-16        25
1  2022-03-07        26
2  2022-03-08        28
3  2022-03-08        29
4  2022-03-08        28
5  2022-03-09        26

使用以下代码绘制箱线图:

maindf.boxplot('Chemical', 'Date')
plt.xticks(rotation=40)
plt.show()

得到的图表X轴日期刻度等距排列,未按实际时间间隔显示(如2021-11-26与2021-11-27应紧密相邻,2021-12-16与2022-03-07应间隔较远)。

问题原因

pandas.DataFrame.boxplot() 默认将Date列视为分类变量,而非时间序列变量。每个日期被当作独立的类别,X轴按类别数量均匀分配位置,完全忽略日期本身的时间差。

修正方案

方法1:使用Seaborn绘制(推荐)

Seaborn的boxplot可以自动识别datetime类型的X轴变量,按实际时间间隔分配箱线图位置,同时保留分组统计:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# 先将Date列转换为datetime类型(确保数据是时间格式)
maindf['Date'] = pd.to_datetime(maindf['Date'])

# 绘制箱线图,x为datetime类型,自动按时间间隔排列
sns.boxplot(data=maindf, x='Date', y='Chemical')
plt.xticks(rotation=40)
plt.tight_layout() # 防止标签被截断
plt.show()

方法2:手动调整Pandas箱线图的X轴位置

如果不想依赖Seaborn,可以手动将日期转换为数值型位置,再设置刻度标签:

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter, DayLocator

# 转换Date列为datetime类型
maindf['Date'] = pd.to_datetime(maindf['Date'])

# 获取唯一日期并排序
unique_dates = sorted(maindf['Date'].unique())
# 将日期转换为timestamp数值(作为X轴位置,反映实际时间间隔)
date_positions = [date.timestamp() for date in unique_dates]
# 生成日期字符串作为刻度标签
date_labels = [date.strftime('%Y-%m-%d') for date in unique_dates]

# 绘制箱线图,指定positions为日期的timestamp值
maindf.boxplot('Chemical', 'Date', positions=date_positions)

# 设置X轴刻度和标签
plt.xticks(date_positions, date_labels, rotation=40)
# 可选:优化X轴日期显示格式
plt.gca().xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
plt.gca().xaxis.set_major_locator(DayLocator(interval=10)) # 调整刻度密度,避免重叠

plt.tight_layout()
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 14:36:19