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

Plotly/Python:如何填充月度时间序列铺满X轴?能否无需扩展数据集

解决Plotly月度堆叠柱状图空隙问题

不用扩展数据集就能搞定,直接调整两个关键参数即可:

  • 把柱子间距设为0:在布局里添加bargap=0,消除柱子之间的空白区域
  • 适配柱子宽度:给每个柱状图系列设置width参数,值对应一个月的毫秒数(比如取28天对应的毫秒数,足够适配大多数月度区间)

修改后的代码示例

假设你用go.Bar创建图表:

# 添加每个堆叠系列时设置宽度
fig.add_trace(go.Bar(
    x=chartdata['Date'],
    y=chartdata['Series1'],
    name='Series1',
    width=pd.Timedelta(days=28).total_seconds() * 1000  # 28天对应的毫秒数
))
fig.add_trace(go.Bar(
    x=chartdata['Date'],
    y=chartdata['Series2'],
    name='Series2',
    width=pd.Timedelta(days=28).total_seconds() * 1000
))

# 原有布局新增bargap=0
fig.update_layout(
    xaxis={
        'title':"",
        'tick0':chartdata[chartdata.Date > date].index[0],
        'dtick':'M1',
        'tickformat':'%b\n%Y',
        'tickangle':-45,
    },
    yaxis={
        'title':"<b>Gross</b> Balances",
        'tickprefix':'$',
        'nticks':20,
        'showgrid':True,
    },
    barmode='stack',
    bargap=0  # 消除柱子间空隙
)

如果用Plotly Express,写法更简洁:

fig = px.bar(chartdata, x='Date', y=['Series1', 'Series2'], barmode='stack')
fig.update_layout(
    xaxis={
        'title':"",
        'tick0':chartdata[chartdata.Date > date].index[0],
        'dtick':'M1',
        'tickformat':'%b\n%Y',
        'tickangle':-45,
    },
    yaxis={
        'title':"<b>Gross</b> Balances",
        'tickprefix':'$',
        'nticks':20,
        'showgrid':True,
    },
    bargap=0
)
fig.update_traces(width=pd.Timedelta(days=28).total_seconds() * 1000)

原理说明:bargap=0让柱子紧密排列,设置width为月度对应的时间长度后,柱子会刚好填满每个月的刻度区间,彻底消除空隙。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 23:49:55