Plotly Dash中直方图与DataTable数据展示不一致问题排查
问题:Plotly直方图合并相邻日期数据,DataTable显示正常
我用Plotly Dash将数据集分别展示为DataTable和直方图,DataTable可准确呈现7天的销售数据,但直方图却将相邻日期(8月15日&16日、17日&18日、19日&20日)的数据合并,仅显示4组结果,找不到原因。
我推测问题与pd.to_datetime的处理逻辑有关:我截取UTC时间范围字符串的前10位转换为单个日期,若不修改Day列的取值,直方图与DataTable的数据展示完全一致。
代码示例
# Incorporate data df = pd.json_normalize(sales.json()['payload'], meta=['interval', 'unitCount', 'orderItemCount', 'orderCount', ['averageUnitPrice', 'currencyCode'], ['totalSales', 'currencyCode']]) # Rename the columns for clarity df.columns = ['Day', 'unitCount', 'orderItemCount', 'orderCount', 'averageUnitPrice', 'curr', 'total sales', 'currency'] print(df) # Convert UTC datetime range to just the first date df['Day'] = pd.to_datetime(df['Day'].str.slice(0,10), format="%Y-%m-%d") print(df) # Initialize the app app = Dash() # App layout app.layout = [ html.Div(children='Amazon sales in the last 7 days'), dash_table.DataTable(data=df.to_dict('records'), page_size=10), dcc.Graph(figure=px.histogram(df, x='Day', y='total sales')) ]
转换前的DataFrame
Day unitCount orderItemCount orderCount averageUnitPrice curr total sales currency 0 2024-08-14T00:00-05:00--2024-08-15T00:00-05:00 28 26 26 29.28 USD 819.72 USD 1 2024-08-15T00:00-05:00--2024-08-16T00:00-05:00 24 19 19 32.49 USD 779.76 USD 2 2024-08-16T00:00-05:00--2024-08-17T00:00-05:00 13 12 12 28.45 USD 369.87 USD 3 2024-08-17T00:00-05:00--2024-08-18T00:00-05:00 18 14 14 25.82 USD 464.82 USD 4 2024-08-18T00:00-05:00--2024-08-19T00:00-05:00 8 8 8 24.99 USD 199.92 USD 5 2024-08-19T00:00-05:00--2024-08-20T00:00-05:00 30 25 25 24.99 USD 749.70 USD 6 2024-08-20T00:00-05:00--2024-08-21T00:00-05:00 40 30 30 28.74 USD 1149.60 USD
转换后的DataFrame
Day unitCount orderItemCount orderCount averageUnitPrice curr total sales currency 0 2024-08-14 28 26 26 29.28 USD 819.72 USD 1 2024-08-15 24 19 19 32.49 USD 779.76 USD 2 2024-08-16 13 12 12 28.45 USD 369.87 USD 3 2024-08-17 18 14 14 25.82 USD 464.82 USD 4 2024-08-18 8 8 8 24.99 USD 199.92 USD 5 2024-08-19 30 25 25 24.99 USD 749.70 USD 6 2024-08-20 40 30 30 28.74 USD 1149.60 USD
解决方案
问题根源不是pd.to_datetime的转换,而是Plotly直方图的默认时间分组逻辑:当x轴为日期类型时,px.histogram会自动按默认时间间隔(这里是2天)分组,导致相邻日期被合并。
提供三种解决方式:
将日期转为字符串类型:让Plotly把每个日期当作独立类别,而非时间轴
修改日期转换代码:df['Day'] = pd.to_datetime(df['Day'].str.slice(0,10), format="%Y-%m-%d").astype(str)强制指定直方图区间数:明确设置nbins为数据的天数(7天),同时指定histfunc为sum确保数值正确累加
修改直方图代码:dcc.Graph(figure=px.histogram(df, x='Day', y='total sales', nbins=7, histfunc='sum'))改用条形图(推荐):你的场景是展示每日销售总额,条形图比直方图更贴合需求,不会出现自动分组问题
修改图表代码:dcc.Graph(figure=px.bar(df, x='Day', y='total sales'))
内容的提问来源于stack exchange,提问作者user3144628
相关产品推荐
相关产品推荐

