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

Plotly绘制Treemap无法显示唯一颜色问题求助

问题描述

绘制Treemap时,发现“new-required-request-property”与“response-body-type-changed”颜色相同,底部橙色的几个类别颜色也重复,需要让每个类别显示独特颜色。使用的代码如下:

import plotly.express as px
import plotly.graph_objects as go
import numpy as np
import plotly.offline as offline


fig = px.treemap(df5, path=['content'],values='count', color='content', color_discrete_sequence=px.colors.qualitative.Pastel, width = 1500,
    height = 800, title='Top 15 Types of Breaking Changes')

fig.update_traces(textinfo='label+value')
fig.update_layout(margin = dict(t=50, l=35, r=25, b=25), template='ggplot2',font=dict(size=20, family='Serif'), paper_bgcolor='rgba(233,233,233,100)')

fig.show()
解决方案

问题出在px.colors.qualitative.Pastel色系的颜色数量不足——这个色系只有9种独特颜色,而你的Treemap有15个类别,Plotly会循环重复使用现有颜色,导致颜色重复。

可以通过两种方式解决:

1. 更换颜色数量更多的定性色系

Plotly提供了多种定性色系,选择颜色数量≥15的即可,比如px.colors.qualitative.D3(20种颜色)、px.colors.qualitative.Alphabet(26种颜色)。修改代码中的color_discrete_sequence参数:

import plotly.express as px
import plotly.graph_objects as go
import numpy as np
import plotly.offline as offline

fig = px.treemap(df5, path=['content'],values='count', color='content', 
                 color_discrete_sequence=px.colors.qualitative.D3,  # 更换为D3色系
                 width = 1500, height = 800, 
                 title='Top 15 Types of Breaking Changes')

fig.update_traces(textinfo='label+value')
fig.update_layout(margin = dict(t=50, l=35, r=25, b=25), 
                  template='ggplot2',
                  font=dict(size=20, family='Serif'), 
                  paper_bgcolor='rgba(233,233,233,100)')

fig.show()

2. 使用自定义颜色列表

如果需要完全自定义的颜色,可以手动创建包含15种独特颜色的列表,传入color_discrete_sequence:

import plotly.express as px
import plotly.graph_objects as go
import numpy as np
import plotly.offline as offline

# 自定义15种独特的十六进制颜色
custom_colors = [
    '#FF6347', '#4682B4', '#32CD32', '#FFD700', '#9400D3',
    '#FF1493', '#1E90FF', '#FF8C00', '#90EE90', '#BA55D3',
    '#F08080', '#20B2AA', '#7B68EE', '#FFB6C1', '#00CED1'
]

fig = px.treemap(df5, path=['content'],values='count', color='content', 
                 color_discrete_sequence=custom_colors,  # 使用自定义颜色
                 width = 1500, height = 800, 
                 title='Top 15 Types of Breaking Changes')

fig.update_traces(textinfo='label+value')
fig.update_layout(margin = dict(t=50, l=35, r=25, b=25), 
                  template='ggplot2',
                  font=dict(size=20, family='Serif'), 
                  paper_bgcolor='rgba(233,233,233,100)')

fig.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 20:12:51