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

如何按总编辑量降序排列Plotly堆叠条形图的X轴?

问题描述

我用Plotly创建了堆叠条形图,用来可视化Google Drive中文件的编辑情况和编辑者信息。源DataFrame包含file_path、emailAddress(编辑者邮箱)、tally三列,当前把file_path设为X轴。我希望所有条形按总编辑量降序排列,但目前没实现,现有代码如下:

import plotly.graph_objects as go

fig = go.Figure()

# Get a list of unique email addresses to create one trace per email address
email_addresses = df['emailAddress'].unique()

# Create a trace for each email address
for email in email_addresses:
    df_filtered = df[df['emailAddress'] == email]
    fig.add_trace(go.Bar(x=df_filtered['path_name'], y=df_filtered['tally'], name=email))

# Update the layout to stack the bars
fig.update_layout(barmode='stack', xaxis_title="File path", yaxis_title="Tally", title="Tally by file path and Email Address")

fig.show()
解决方案

要实现按每个文件的总编辑量降序排列,需要先计算每个文件的总编辑数,再基于这个总数对文件路径排序,最后用排序后的顺序统一绘制所有trace。具体修改如下:

import plotly.graph_objects as go

fig = go.Figure()

# 1. 计算每个文件的总tally,按降序排序并提取文件路径列表
file_totals = df.groupby('file_path')['tally'].sum().sort_values(ascending=False)
sorted_file_paths = file_totals.index.tolist()

# 2. 获取唯一邮箱列表
email_addresses = df['emailAddress'].unique()

# 3. 为每个邮箱创建trace,统一使用排序后的文件路径
for email in email_addresses:
    # 筛选当前邮箱数据,按排序后的路径重新索引,缺失数据补0
    df_filtered = (
        df[df['emailAddress'] == email]
        .set_index('file_path')
        .reindex(sorted_file_paths)
        .fillna(0)
        .reset_index()
    )
    fig.add_trace(go.Bar(x=df_filtered['file_path'], y=df_filtered['tally'], name=email))

# 4. 更新布局
fig.update_layout(
    barmode='stack',
    xaxis_title="File path",
    yaxis_title="Tally",
    title="Tally by file path and Email Address (Sorted by Total Tally)"
)

fig.show()

关键说明

  • 原代码的问题在于每个trace的X轴是各自筛选后的零散数据,没有统一的排序逻辑,导致整体X轴顺序混乱。
  • 通过先计算每个文件的总编辑量并排序,让所有trace使用相同的排序后文件路径列表,就能保证堆叠条形图按总编辑量降序排列,同时补全缺失数据避免条形错位。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 00:39:55