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

Plotly go.Bar绘制问题:降序取Top5属性并设置节点差异化颜色

Plotly横向条形图Top5节点展示及颜色差异化解决方案

问题背景

现有包含节点名称、degree(度)、connectivity(连通性)的DataFrame stat_df,数据示例:

node                      degree  connectivity
0  Antonio da Correggio     0.142857        0.5
1  Adriaen van der Werff    0.011905        0.4
2  Agnolo Gaddi             0.000000        0.3
3  Filippino Lippi          0.071429        0.1

需求:用Plotly的go.Bar绘制两个横向条形图,分别展示degree和connectivity的Top5节点,且每个节点的条形使用不同颜色。原代码因列名不匹配、未处理颜色等问题,在ascending=False时无法正常运行。

问题分析

原代码核心问题:

  • 列名大小写不匹配:DataFrame中列名为小写的degree/connectivity,代码中误用大写Degree/Connectivity,导致排序逻辑失效
  • 重复调用sort_values,效率低且易出错
  • 未设置条形颜色差异化,无法区分不同节点
  • 横向条形图默认y轴顺序与Top5展示逻辑冲突(默认从上到下为升序,Top5需要从上到下为降序)

解决方案

步骤1:提取Top5数据并统一处理

先分别筛选出两个指标的Top5数据,避免重复排序:

# 提取degree Top5,按降序排序
top5_degree = stat_df.sort_values('degree', ascending=False).head(5)
# 提取connectivity Top5,按降序排序
top5_connectivity = stat_df.sort_values('connectivity', ascending=False).head(5)

步骤2:为节点分配唯一颜色

使用Plotly内置颜色序列,为每个节点分配专属颜色:

import plotly.express as px

# 获取Plotly默认定性颜色序列
color_sequence = px.colors.qualitative.Plotly
# 为所有节点生成颜色映射,确保同节点颜色一致
node_colors = {node: color_sequence[i % len(color_sequence)] for i, node in enumerate(stat_df['node'].unique())}

步骤3:创建带差异化颜色的Bar trace

为每个指标的Top5数据创建Bar对象,逐个指定条形颜色:

import plotly.graph_objects as go

# Degree的条形图数据
trace_degree = go.Bar(
    x=top5_degree['degree'],
    y=top5_degree['node'],
    orientation='h',
    name='Degree',
    # 为每个节点匹配对应颜色
    marker_color=[node_colors[node] for node in top5_degree['node']]
)

# Connectivity的条形图数据
trace_connectivity = go.Bar(
    x=top5_connectivity['connectivity'],
    y=top5_connectivity['node'],
    orientation='h',
    name='Connectivity',
    marker_color=[node_colors[node] for node in top5_connectivity['node']]
)

步骤4:调整布局并展示图表

设置y轴顺序为降序,确保Top5节点从上到下按数值大小排列:

fig = go.Figure(data=[trace_degree, trace_connectivity])

fig.update_layout(
    title='Top5节点Degree与Connectivity对比',
    yaxis={'categoryorder': 'total ascending'},  # 适配横向条形图,实现从上到下数值递减
    barmode='group',  # 分组展示两个指标的条形
    xaxis_title='数值',
    yaxis_title='节点名称'
)

fig.show()

完整可运行代码

import pandas as pd
import plotly.graph_objects as go
import plotly.express as px

# 初始化示例DataFrame(替换为你的真实数据)
stat_df = pd.DataFrame({
    'node': ['Antonio da Correggio', 'Adriaen van der Werff', 'Agnolo Gaddi', 'Filippino Lippi'],
    'degree': [0.142857, 0.011905, 0.000000, 0.071429],
    'connectivity': [0.5, 0.4, 0.3, 0.1]
})

# 提取Top5数据
top5_degree = stat_df.sort_values('degree', ascending=False).head(5)
top5_connectivity = stat_df.sort_values('connectivity', ascending=False).head(5)

# 节点颜色映射
color_sequence = px.colors.qualitative.Plotly
node_colors = {node: color_sequence[i % len(color_sequence)] for i, node in enumerate(stat_df['node'].unique())}

# 创建条形图trace
trace_degree = go.Bar(
    x=top5_degree['degree'],
    y=top5_degree['node'],
    orientation='h',
    name='Degree',
    marker_color=[node_colors[node] for node in top5_degree['node']]
)

trace_connectivity = go.Bar(
    x=top5_connectivity['connectivity'],
    y=top5_connectivity['node'],
    orientation='h',
    name='Connectivity',
    marker_color=[node_colors[node] for node in top5_connectivity['node']]
)

# 布局配置与展示
fig = go.Figure(data=[trace_degree, trace_connectivity])
fig.update_layout(
    title='Top5节点Degree与Connectivity对比',
    yaxis={'categoryorder': 'total ascending'},
    barmode='group',
    xaxis_title='数值',
    yaxis_title='节点名称'
)

fig.show()

效果说明

  • 相同节点在两个指标图表中颜色一致,不同节点颜色唯一
  • 横向条形图从上到下展示Top5节点(数值从大到小)
  • 修复了原代码中ascending=False时无法运行的问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 00:03:26