使用Plotly Express px.bar绘图时日期轴偏移问题求助
Plotly柱状图X轴日期范围异常问题解决
问题描述
用Plotly Express的px.bar绘制2015-2022年的年度收益柱状图,但生成的图表X轴显示范围变成了2016-2023年,和数据实际时间范围不符。
使用的代码如下:
# plotting the yearly % returns fig = px.bar(yearly, x='Date', y=['Model','Benchmark'], title="Yearly Profit", labels={'value': 'Percent', 'variable':''},barmode = 'group') new = {'Model':'Model %', 'Benchmark': bMark + ' %'} # Change the column names for the legend fig.for_each_trace(lambda t: t.update(name = new[t.name])) fig.show()
数据集yearly内容:
| 序号 | Date | Model | Benchmark |
|---|---|---|---|
| 0 | 2015-12-31 00:00:00 | 72.7922 | 1.23411 |
| 1 | 2016-12-30 00:00:00 | 27.1839 | 11.9969 |
| 2 | 2017-12-29 00:00:00 | 39.9856 | 21.7039 |
| 3 | 2018-12-31 00:00:00 | 15.6401 | -4.56891 |
| 4 | 2019-12-31 00:00:00 | 42.3679 | 31.2216 |
| 5 | 2020-12-31 00:00:00 | 211.67 | 18.3307 |
| 6 | 2021-12-31 00:00:00 | 56.0862 | 28.7285 |
| 7 | 2022-10-31 00:00:00 | -1.97482 | -17.7437 |
图表显示X轴从2016年开始,到2023年结束,数据点却集中在2015-2022的对应位置。
原因分析
这是Plotly对连续时间轴的自动刻度调整机制导致的:
- 当X轴为日期时间类型时,Plotly会自动计算并扩展刻度范围,让轴的显示更规整(比如对齐年度起始/结束点),哪怕数据里的日期不是严格年末(如2022年是10月31日),也会自动延伸到下一个年度边界。
- 连续时间轴的刻度按时间区间划分,Plotly会根据数据跨度自动生成刻度,容易出现超出实际数据范围的情况。
解决方案
方法1:将X轴转为离散年份类别(推荐)
提取Date列的年份作为字符串,把X轴改为离散类别轴,Plotly只会显示数据中存在的年份,不会自动扩展范围。
修改后代码:
# 提取年份作为新列 yearly['Year'] = yearly['Date'].dt.year.astype(str) # 用Year作为x轴绘制柱状图 fig = px.bar(yearly, x='Year', y=['Model','Benchmark'], title="Yearly Profit", labels={'value': 'Percent', 'variable':''}, barmode='group') new = {'Model':'Model %', 'Benchmark': bMark + ' %'} fig.for_each_trace(lambda t: t.update(name=new[t.name])) fig.show()
方法2:手动设置X轴范围
如果要保留日期时间类型的X轴,可以手动指定轴的范围,强制限定在2015年初到2022年末:
fig = px.bar(yearly, x='Date', y=['Model','Benchmark'], title="Yearly Profit", labels={'value': 'Percent', 'variable':''}, barmode='group') new = {'Model':'Model %', 'Benchmark': bMark + ' %'} fig.for_each_trace(lambda t: t.update(name=new[t.name])) # 设置X轴范围为2015-01-01到2022-12-31 fig.update_xaxes(range=['2015-01-01', '2022-12-31']) fig.show()
内容的提问来源于stack exchange,提问作者supplydemand
相关产品推荐
相关产品推荐

