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

Plotly Express直方图设置fixedrange后rug图x轴错位如何解决

问题原因

当你给px.histogram传入marginal='rug'参数时,Plotly会自动生成上下排布的两个子图:上方是主直方图,下方是rug分布图,两个子图各有独立的x轴配置。你之前调用update_xaxes时默认只修改了主直方图的x轴,rug子图的x轴没有同步设置范围和fixedrange属性,因此出现了范围不一致、点位偏移的问题。

解决方案

修改x轴配置的代码,匹配所有x轴同步设置相同的范围和fixedrange属性即可,无需改动其他逻辑。

关键修改代码片段

把原回调函数中更新x轴的代码:

histogram.update_xaxes(fixedrange=x_zoomable)

替换为:

# 同步所有x轴(主直方图+rug图)的范围与缩放锁定配置
histogram.update_xaxes(
    range=[start, end],
    fixedrange=x_zoomable,
    selector={"type": "x"}
)

修改后完整可运行代码

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.express as px
import pandas as pd
import dash_daq as daq


app = dash.Dash(__name__)

app.layout = html.Div([
    dcc.Graph(id="graph"),
    html.Label("Make x axis zoomable"),
    daq.ToggleSwitch(
            id='x_toggle_switch',
            value=False
        )
])


@app.callback(
    Output("graph", "figure"),
    [Input('x_toggle_switch', 'value')])
def make_x_zoomable(x_zoomable):
    start, end = 0, 25
    df = pd.DataFrame({'x': [0, 5, 10, 15, 20, 25]})
    histogram = px.histogram(df, x='x',
                             nbins=end - start + 1,
                             range_x=[start, end],
                             marginal='rug',
                             barmode='overlay',
                             template='plotly_white')
    histogram.update_layout(showlegend=False, yaxis_title='y', xaxis_title='x')

    # 同步所有x轴配置,解决rug图偏移问题
    histogram.update_xaxes(
        range=[start, end],
        fixedrange=x_zoomable,
        selector={"type": "x"}
    )
    histogram.update_yaxes(fixedrange=True)

    return histogram


app.run_server(debug=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 07:45:04