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

Python Plotly:透视表生成异常图例问题咨询

Fixing Abnormal Legend When Visualizing Pandas Pivot Table with Plotly

It looks like the issue comes from the multi-level column index generated by your pivot table. When you run pd.pivot_table() without explicitly handling the value column's structure, you end up with a MultiIndex where the top level is your original 'Total' column name, and the lower level holds the 'Type' values. Plotly doesn't handle this nested column structure well by default, which leads to messy, duplicated, or confusing legend entries.

Step 1: Fix the Pivot Table Column Structure

Let's adjust the pivot table to use a flat column index instead of a multi-level one. You have two straightforward options:

Option 1: Flatten an Existing MultiIndex

If you already have the dfA pivot table, strip out the top-level 'Total' index and keep only the 'Type' values as column names:

# Remove the top-level 'Total' label from columns
dfA.columns = dfA.columns.get_level_values(1)
# Optional: Clear the column index name for cleaner Plotly output
dfA = dfA.rename_axis(columns=None)

Option 2: Generate a Flat Pivot Table Directly

When creating the pivot table, explicitly define the values parameter and use aggfunc (since pivot tables default to calculating means—use sum here to correctly aggregate your publication counts):

dfA = pd.pivot_table(
    dfPub,
    index=['Year'],
    columns=['Type'],
    values='Total',  # Explicitly target the 'Total' column
    fill_value=0,
    aggfunc='sum'    # Aggregate by sum to get accurate total counts
)
# Clear the column index name to avoid extra labels in Plotly
dfA = dfA.rename_axis(columns=None)

Step 2: Visualize with Plotly (Clean Legend Now!)

With the flat column structure, Plotly will generate a clean legend showing only your publication types. Here's an example using Plotly Express:

import plotly.express as px

# Create a line chart (swap to bar/area chart as needed)
fig = px.line(
    dfA,
    x=dfA.index,
    y=dfA.columns,
    title='Publications by Type Over Years',
    labels={'value': 'Total Publications', 'variable': 'Publication Type'}
)

fig.update_layout(legend_title_text='Publication Type')
fig.show()

Why This Works

Your original pivot table had a MultiIndex like [('Total', 'Book'), ('Total', 'Book Chapter'), ...]. Plotly was interpreting these full tuples as series names, leading to confusing legend entries (like "Total.Book" or repeated "Total" labels). By flattening the columns to just the 'Type' values, Plotly correctly maps each column to a distinct publication type in the legend.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:13:30