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

如何在Plotly/Dash中调整柱状图bin宽度,解决数据过窄不可见问题

问题解决方法

核心原因

你使用的xbins是Plotly直方图(px.histogram)的专属参数,而你当前调用的是普通柱状图接口px.bar,所以该配置不会生效,才会出现设置后无变化的情况。

解决方案1:继续使用px.bar动态适配宽度

因为你用了barmode="group"分组模式,每组有正负两个柱子,我们可以根据当前选中股票的行权价间距动态设置柱子宽度,让柱子占满可用空间:

@app.callback(
    Output("bar-chart", "figure"), 
    [Input("dropdown", "value")])
def gex_per_strike(ticker):
    mask = GEX['ticker'] == ticker
    df = GEX[mask].copy()
    fig = px.bar(df, x="strike", y="net_GEX", 
                 color= 'pos_neg', 
                 barmode="group", 
                 title = ('Gamma Exposure for ' + ticker),
                 color_discrete_sequence = ['#DC143C','#7FFF00'])
    # 动态计算柱子宽度:先算行权价最小间隔
    strikes_sorted = sorted(df['strike'].unique())
    if len(strikes_sorted)>=2:
        min_gap = min([strikes_sorted[i+1] - strikes_sorted[i] for i in range(len(strikes_sorted)-1)])
    else:
        min_gap = 1
    # 分组模式下两个柱子总宽度占间隔的90%,单个占45%
    bar_width = min_gap * 0.45
    fig.update_traces(width=bar_width)
    return fig

解决方案2:换用直方图实现分箱逻辑

如果你的需求本身就是对行权价做分箱统计,直接使用px.histogram接口即可,这时候xbins参数会生效,还可以根据当前数据范围动态调整分箱大小:

@app.callback(
    Output("bar-chart", "figure"), 
    [Input("dropdown", "value")])
def gex_per_strike(ticker):
    mask = GEX['ticker'] == ticker
    df = GEX[mask].copy()
    # 动态计算分箱大小:按当前行权价范围分50个箱,可根据需求调整数量
    strike_min = df['strike'].min()
    strike_max = df['strike'].max()
    bin_size = (strike_max - strike_min)/50
    fig = px.histogram(df, x="strike", y="net_GEX",
                 color= 'pos_neg', 
                 barmode="group", 
                 title = ('Gamma Exposure for ' + ticker),
                 color_discrete_sequence = ['#DC143C','#7FFF00'])
    fig.update_traces(xbins=dict(
        start = strike_min,
        end = strike_max,
        size = bin_size
    ))
    return fig

额外优化建议

你当前设置的图表样式{'width': '90vh', 'height': '90vh'}是用视口高度做宽度,建议改成{'width': '90%', 'height': '90vh'}适配不同屏幕宽度,显示效果更稳定。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 03:15:08