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

使用Plotly Express绘制水平条形图未显示全部数据求助

解决Plotly Express水平条形图仅显示部分数据的问题

你的问题核心原因是y轴使用的birth_country_current存在重复值,Plotly默认会将同一国家的条目合并展示(堆叠或分组),导致你看到的是不同国家的数量(4个),而非原始的20条记录。以下分两种场景给出解决方案:


场景1:需要显示全部20条独立记录的条形

如果要让每条记录都显示为单独的条形,需要给y轴设置唯一标识,避免同一国家的条目被合并。可以通过组合国家和类别生成唯一标签:

# 生成国家+类别的唯一标签列
top20_merged['country_category'] = top20_merged['birth_country_current'] + ' - ' + top20_merged['category']

# 使用唯一标签作为y轴
top20_cat_chart = px.bar(
    x=top20_merged.cat_prize,
    y=top20_merged.country_category,
    color=top20_merged.category,
    orientation="h",
    title="Top 20 Countries by No. Prizes & Category"
)

top20_cat_chart.update_layout(
    xaxis_title="No. Prizes",
    yaxis_title="Country - Category"
)

top20_cat_chart.show()

场景2:按国家分组展示各类别获奖数(确保所有数据被加载)

如果你的需求是按国家分组,每个国家下展示对应类别的获奖数据,可通过调整条形模式并强制显示所有国家:

top20_cat_chart = px.bar(
    x=top20_merged.cat_prize,
    y=top20_merged.birth_country_current,
    color=top20_merged.category,
    orientation="h",
    barmode='group',  # 可选'stack'实现堆叠显示,根据需求选择
    title="Top 20 Countries by No. Prizes & Category"
)

top20_cat_chart.update_layout(
    xaxis_title="No. Prizes",
    yaxis_title="Country"
)

# 反转y轴(水平条形图常用设置,确保数据顺序符合直觉)并强制显示所有国家
top20_cat_chart.update_yaxes(autorange='reversed')

top20_cat_chart.show()

前置检查:确认数据结构

可以先执行以下代码确认数据的唯一性,排查是否存在重复组合:

# 查看不同国家的数量
print("不同国家数量:", top20_merged['birth_country_current'].nunique())
# 查看重复的国家-类别组合数
print("重复的国家-类别组合数:", top20_merged[['birth_country_current', 'category']].duplicated().sum())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 17:32:58