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

Plotly Python中contour的labelformat参数设置后无效果如何解决?

Plotly等高线标签不显示问题解决

问题根源

你代码中设置contours=dict(type='constraint')是核心问题:当contours类型为constraint时,Plotly不会启用标签显示功能,哪怕设置了showlabels=True也无效,和是否有激活按钮无关。

修改方案

  1. 将contours的type改为'levels',这是用于显示多个等高线层级的标准模式,支持标签渲染。
  2. 对应type='levels',层级参数要使用levels而非value。
  3. 确保调用fig.show()来渲染图形(脚本运行场景下容易遗漏)。

修改后的完整代码

import numpy as np
import plotly.graph_objects as go

x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
z = np.sin(X) * np.cos(Y)

levels = [0.2, 0.5, -0.2, -0.5]
    
fig = go.Figure()

fig.add_contour(
    x=x, y=y, z=z,
    contours_coloring='none',
    line=dict(color='black'),
    contours=dict(
        showlabels=True,
        labelformat=".2f V",
        type='levels',
        levels=levels,
    )
)
fig.update_layout(showlegend=True)
fig.show()

补充说明

  • d3-format是Plotly依赖的数值格式化规则,.2f表示保留两位小数,你直接写.2f V在Plotly 6.0+版本中可以正常解析,会自动为格式化后的数值添加单位。
  • type='constraint'仅适用于绘制特定值的约束线,该模式下不支持标签功能,若仅需显示特定层级的等高线并加标签,仍需使用type='levels'并指定对应层级列表。

内容的提问来源于stack exchange,提问作者H.C.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 07:41:02