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

Plotly Graph Objects中log轴搭配range参数不生效问题

问题根因

Plotly 对数坐标轴的range参数规则和线性轴不一致:对数轴下接收的范围值是目标边界的10为底对数值,而非原始业务数值。你代码中传入range=[0,5],实际对应的原始数值范围是$10^0=1$ 到 $10^5=100000$,和你想要的展示区间完全不匹配,自然无法按预期渲染。
另外两处配置错误也会导致异常:

  • 初始化Figure时传入的layout_xaxis_range=[1,5]属于冗余配置,会和后续x轴参数产生覆盖冲突
  • 你的评分数据最小值为6、最大值为27,原代码设置的x轴上限5无法容纳所有条形,会导致条形显示截断
修复步骤
  • 删除初始化Figure时冗余的layout_xaxis_range参数
  • 对数轴range按对数值传入:要覆盖1~32左右的评分区间(适配最大评分27),对应对数值为[0, 1.5](因为$10^{1.5}\approx31.6$)
  • 把灰色背景参考条的固定x值从5调整为30,和x轴上限匹配,保证参考条撑满轴宽度
修复后完整代码
import plotly.graph_objects as go

# 替换为你实际的top_10评分数据即可
rating_values = [27, 18, 12, 6, 27, 18, 12, 6, 10, 10]
worker_labels = [f'Worker {i}' for i in range(1, 11)]

fig = go.Figure(
        go.Bar(
            x=[30]*10,
            y=worker_labels,
            text=rating_values,
            textposition="inside",
            textfont=dict(color="white"),
            orientation="h",
            marker_color="grey",
        )
)

fig.add_trace(
    go.Bar(
        x=rating_values,
        y=worker_labels,
        orientation="h",
    )
)
fig.update_layout(
    title='Top 10 Workers', 
    barmode="overlay", 
    showlegend=False, 
    template="presentation",
)
fig.update_yaxes(
    tickmode="array",
    categoryorder="total ascending",
    tickvals=worker_labels,
    ticktext=worker_labels,
    ticklabelposition="inside",
    tickfont=dict(color="white"),
)
fig.update_xaxes(
    range=[0, 1.5],
    type='log',
    dtick=1
)
fig.show()
注意事项
  • 对数轴无法展示0值,如果你的评分数据包含0,需要先做偏移处理(如所有评分统一+1)再配置log轴
  • 如果后续需要调整x轴展示范围,直接将目标上下限取10为底的对数传入range即可,例如要展示2~100的范围,对应range参数为[0.3, 2]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 00:12:17