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

如何让Matplotlib饼图标签与DataFrame的对应数值正确匹配?

解决饼图标签与数值不匹配的问题

问题根源:combined_df.groupby(['Continent'])['total_consumption'].sum()返回的是按大陆名称排序后的求和结果,而combined_df['Continent'].unique()返回的是大陆在原数据中首次出现的顺序,两者顺序不一致,导致标签和对应扇区错位。

修正后的代码:

import seaborn as sns
import matplotlib.pyplot as plt

# 先计算分组求和数据,确保索引与数值一一对应
continent_consumption = combined_df.groupby(['Continent'])['total_consumption'].sum()
# 爆炸扇区的顺序要与分组后的索引顺序一致(此处对应Asia扇区爆炸)
explode = [0, 0.1, 0, 0, 0, 0]
palette_color = sns.color_palette('pastel')

# 直接使用分组结果的索引作为标签,保证顺序匹配
fig, _ = plt.pie(continent_consumption, 
                 colors=palette_color,
                 labels=continent_consumption.index,
                 explode=explode, 
                 autopct='%.0f%%', 
                 labeldistance=0.9)
plt.show()

说明:

  • 先将分组求和结果存入变量continent_consumption,它的索引就是大陆名称,且与对应求和值严格对应
  • 用continent_consumption.index作为labels参数,彻底解决标签与扇区错位的问题
  • 确认explode的顺序和分组后的索引顺序匹配(根据你给出的数值顺序,explode[1] = 0.1对应Asia,是正确的)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 07:45:26