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

Matplotlib X轴如何显示DataFrame中的精确自定义日期?

问题:如何让Seaborn折线图X轴显示DataFrame中的精确日期?

我用以下代码绘制折线图:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib.dates as mdates


dates = pd.date_range('2020-03-31', '2024-06-30', freq='Q')
my_df =pd.DataFrame({'dates': dates, 
                        'type_a': [np.nan]*10 + list(range(0, len(dates)-10)),
                        'type_b': range(len(dates), 2*len(dates))})
    
my_df = my_df.melt(id_vars='dates', value_vars = ['type_a', 'type_b'])
my_df.dates = my_df.dates.dt.date

gfg = sns.lineplot(x='dates', y='value', hue='variable', 
                  data=my_df, estimator=None)
gfg.xaxis.set_major_locator(mdates.MonthLocator(interval=3))
gfg.set_xticklabels(gfg.get_xticklabels(), rotation=90)
gfg.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))

绘图后X轴并未显示DataFrame中的精确日期,我尝试将gfg.xaxis.set_major_locator(mdates.MonthLocator(interval=3))替换为gfg.xaxis.set_major_locator(mdates.DayLocator(interval=90)),但仍未达到预期效果。请问如何让X轴显示DataFrame中的精确日期?


解决方案

要让X轴显示DataFrame里的精确日期,关键调整两点:

  • 保留dates列的datetime64原生类型,不要转为dt.date对象,matplotlib的日期工具对原生datetime类型支持更准确;
  • 使用FixedLocator直接指定刻度位置为DataFrame中的精确日期,强制显示这些值。

修改后的完整代码如下:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib.dates as mdates


dates = pd.date_range('2020-03-31', '2024-06-30', freq='Q')
my_df =pd.DataFrame({'dates': dates, 
                        'type_a': [np.nan]*10 + list(range(0, len(dates)-10)),
                        'type_b': range(len(dates), 2*len(dates))})
    
my_df = my_df.melt(id_vars='dates', value_vars = ['type_a', 'type_b'])
# 移除转为dt.date的操作,保留datetime64类型
# my_df.dates = my_df.dates.dt.date

gfg = sns.lineplot(x='dates', y='value', hue='variable', 
                  data=my_df, estimator=None)

# 使用FixedLocator设置精确的日期刻度
gfg.xaxis.set_major_locator(mdates.FixedLocator(my_df['dates'].unique()))
# 格式化日期显示
gfg.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
# 旋转刻度标签避免重叠
plt.xticks(rotation=90)
plt.tight_layout()  # 调整布局,防止标签被画布边缘截断
plt.show()

关键修改说明:

  1. 删除my_df.dates = my_df.dates.dt.date,让dates列保持datetime64类型,确保matplotlib能精准识别日期值;
  2. 用mdates.FixedLocator(my_df['dates'].unique())替代原有定位器,直接将DataFrame中所有唯一的精确日期设为X轴刻度;
  3. 改用plt.xticks(rotation=90)设置标签旋转,避免手动设置标签可能出现的错位问题;
  4. 添加plt.tight_layout()确保刻度标签完整显示,不会被画布边缘截断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 18:12:43