You need to enable JavaScript to run this app. Plotly矩形树图(treemap)如何将连续色条从右侧移至上下侧设为横向展示
优惠活动
大模型
产品
解决方案
定价
更多

Plotly矩形树图(treemap)如何将连续色条从右侧移至上下侧设为横向展示

调整Plotly Treemap连续色条位置为横向展示的方法

常见配置误区

使用legend参数调整连续色条位置完全不生效——legend是离散分类图例的专属配置,连续数值映射生成的色条不受legend管辖,这就是调整没有达到预期的核心原因。

连续色条的所有样式、位置、方向调整,都要通过update_coloraxes方法下的colorbar配置项实现。

基础可复现代码

import plotly.express as px
import numpy as np
df = px.data.gapminder().query("year == 2007")
df["world"] = "world" # 用于生成单一根节点
fig = px.treemap(df, path=['world', 'continent', 'country'], values='pop',
                  color='lifeExp', hover_data=['iso_alpha'],
                  color_continuous_scale='RdBu',
                  color_continuous_midpoint=np.average(df['lifeExp'], weights=df['pop']))
fig.show()

具体调整方案

核心配置参数说明

要实现横向色条展示、并将其移动到顶部/底部,需要在colorbar中设置两类参数:

  • 方向参数:将orientation设为h,替换默认的v(纵向)模式,即可生成横向延伸的色条
  • 位置参数:通过x/y定义色条的锚点坐标,配合xanchor/yanchor定义锚定规则,结合thickness(色条粗细)、len(色条长度)调整视觉效果

场景1:横向色条放置在图表底部

fig.update_coloraxes(
    colorbar=dict(
        orientation="h",
        yanchor="top",
        y=-0.1,
        xanchor="center",
        x=0.5,
        thickness=15,
        len=0.8
    )
)

场景2:横向色条放置在图表顶部

fig.update_coloraxes(
    colorbar=dict(
        orientation="h",
        yanchor="bottom",
        y=1.02,
        xanchor="center",
        x=0.5,
        thickness=15,
        len=0.8
    )
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.28 01:06:03