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

Plotly绘制Python3 3D曲面图:如何添加颜色条标题及单位?

Plotly 3D曲面图颜色条标题与单位设置方案

解决colorbar报错问题

你之前用fig.update_layout(colorbar=...)报错,是因为colorbar属于曲面图的轨迹(trace)属性,不是全局布局(layout)的直接属性,不能直接在update_layout里设置。

两种正确设置方式

  1. 创建曲面时直接指定colorbar
import plotly.graph_objects as go
import numpy as np

# 生成示例数据
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
x, y = np.meshgrid(x, y)
z = np.sin(np.sqrt(x**2 + y**2))

# 在Surface trace中设置colorbar
fig = go.Figure(data=[go.Surface(
    x=x, y=y, z=z,
    colorbar=dict(
        title='Temperature(K)',  # 颜色条标题
        titleside='right'        # 标题显示在右侧
    )
)])

fig.show()
  1. 通过update_traces修改已有图表
    如果已经创建好图表,用update_traces批量修改轨迹的colorbar属性:
# 假设fig已存在
fig.update_traces(
    colorbar=dict(
        title='Temperature(K)',
        titleside='right'
    )
)

给颜色条数值添加单位

通过colorbar的tickformat参数可以给刻度值添加单位,比如设置为保留两位小数并加上K单位:

fig.update_traces(
    colorbar=dict(
        title='Temperature',
        titleside='right',
        tickformat='.2f K'  # 刻度值格式:保留2位小数 + 单位K
    )
)

如果需要更复杂的格式,还可以用d3格式语法自定义,比如整数单位格式tickformat='d K'。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 21:57:04