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

Plotly Express折线图分组日期滞后30天问题求助

解决分组日期为字符串导致的日期运算问题

问题根源

你当前用dt.strftime('%Y-%m')生成的year_month是字符串类型,而非datetime日期对象,这直接导致无法直接通过timedelta/relativedelta进行日期加减,同时Plotly对字符串日期的解析逻辑可能让你产生“日期滞后”的错觉。

解决方案:保留分组字段的日期类型

核心思路是将分组用的年月转换为可运算的datetime类型(比如每月第一天),既不影响分组求和的结果,又能支持正常的日期操作。

方法1:生成分组字段时直接用datetime类型

替换原来生成year_month的代码,用dt.floor('M')获取每个日期所属月份的第一天(或用dt.to_period('M').dt.end_time获取最后一天):

# 替换原来的strftime代码
df['year_month'] = df['Date'].dt.floor('M')  # 得到每月第一天的datetime对象,如2022-06-01 00:00:00

方法2:将已有字符串类型的年月转回datetime

如果已经生成了字符串格式的year_month,可以通过以下方式转换为datetime:

Income_Expense['year_month'] = pd.to_datetime(Income_Expense['year_month'])

修改后的完整代码

import pandas as pd
from datetime import datetime, timedelta
import plotly.express as px
import sqlite3
import numpy as np
from dateutil.relativedelta import relativedelta


data = {
'Transaction_type':[ 'Debit', 'Debit', 'Credit','Debit','Debit','Debit', 'Debit', 'Credit','Debit','Debit'],
    'Amount': [40,150,1000,60,80,120, 80, 1000,500,80]
}

df = pd.DataFrame(data)
df['Date'] = pd.date_range(start='6/1/2022',end='7/30/2022', periods = len(df))

df['Date'] = pd.to_datetime(df['Date'])
# 关键修改:生成datetime类型的年月分组字段(每月第一天)
df['year_month'] = df['Date'].dt.floor('M')


#Income Expense Visual
Income_Expense = df.copy()
# 注意:替换操作匹配原数据大小写
Income_Expense.Transaction_type.replace(['Credit'], 'Income', inplace=True) 
Income_Expense.Transaction_type.replace(['Debit'], 'Expense', inplace=True)

Income_Expense = pd.pivot_table(Income_Expense, values = ['Amount'], index = ['Transaction_type', 'year_month'],aggfunc=sum).reset_index()

# Plotly自动识别datetime类型x轴,显示效果与原字符串一致但支持日期运算
scatter_plot = px.line(Income_Expense, x = 'year_month', y = 'Amount', color = 'Transaction_type', title = 'Income and Expense', color_discrete_sequence= ['red','green'],
                       category_orders= {'Transaction_type': ['Expense', 'Income']})  # 修正原代码中category_orders的错误键
scatter_plot.update_layout(legend_traceorder = 'reversed')
scatter_plot.update_layout(yaxis_tickformat = ',')
# 自定义x轴显示为年月格式
scatter_plot.update_xaxes(tickformat='%Y-%m')

scatter_plot.show()

额外说明

  1. 修正了原代码中category_orders的错误键(原代码写的是'Cash Flow',实际应为'Transaction_type')
  2. 转换为datetime类型后,可直接进行日期加减操作,例如获取上一个月的数据:
    target_month = df['year_month'].max() - relativedelta(months=1)
    filtered_data = Income_Expense[Income_Expense['year_month'] == target_month]
    
  3. Plotly对datetime类型x轴支持更丰富的交互(如范围选择、自动缩放),体验优于字符串日期

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 01:40:31