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

Python中Plotly如何实现Treemap树图按分类(如大洲)设置颜色

Plotly Treemap按大洲分类设置颜色实现方法

你原来的代码是按照人均寿命的连续数值配置颜色,只需要修改两个核心参数即可实现按大洲分类配色:

  1. 将color参数值从lifeExp改为分类列continent
  2. 如需自定义每个大洲的具体色值,新增color_discrete_map参数传入色值映射即可,不需要自定义的话用默认离散配色也可以

完整实现代码

import plotly.express as px
import numpy as np
df = px.data.gapminder().query("year == 2007")
# 自定义大洲颜色映射,可按需修改色值
continent_color = {
    'Asia': '#FF5733',
    'Europe': '#3377FF',
    'Africa': '#33FF57',
    'Americas': '#FFC300',
    'Oceania': '#A832FF'
}
fig = px.treemap(df, path=[px.Constant("world"), 'continent', 'country'], values='pop',
                  color='continent', hover_data=['iso_alpha'],
                  color_discrete_map=continent_color)
fig.update_layout(margin = dict(t=50, l=25, r=25, b=25))
fig.show()

效果说明

  • 同一大洲下的所有国家会自动继承所属大洲的配色,层级视觉区分明显
  • 如果不需要自定义颜色,删除color_discrete_map参数即可使用Plotly默认的离散分类配色

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 10:36:03