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

基于pd.DataFrame绘制多站点饼图/柱状图及最值提取技术求助

问题描述

数据情况

以下是我的pd.DataFrame数据:

SiteABCD
Blue413911
Green1123020
Yellow12233
Red201440

需求

  1. 为每个Site绘制展示比例的饼图或柱状图;
  2. 编写代码输出各指标(A、B、C、D)最值对应的Site(如Blue、Green等)。

尝试过的代码(未达预期)

  • 代码1:
p = df[["C"]].value_counts(sort="False").plot(kind='bar')
  • 代码2:
x_axis = df.iloc[1].values
y_axis = df.iloc[1].values
plt.bar(x_axis,y_axis,color = 'b')
plt.xlabel('Site')
plt.ylabel('Colour')
plt.show()

解决方案

一、为每个Site绘制比例图表

1. 绘制每个Site的指标占比饼图

每个Site的A、B、C、D四个指标可看作该Site的各项数值,为每个Site单独生成饼图展示占比:

import pandas as pd
import matplotlib.pyplot as plt

# 构造DataFrame
data = {
    'Site': ['Blue', 'Green', 'Yellow', 'Red'],
    'A': [4, 1, 12, 20],
    'B': [13, 12, 2, 14],
    'C': [9, 30, 3, 4],
    'D': [11, 20, 3, 0]
}
df = pd.DataFrame(data).set_index('Site')

# 遍历每个Site绘制饼图
for site in df.index:
    plt.figure(figsize=(6,6))
    site_data = df.loc[site]
    # 过滤值为0的指标(比如Red的D值)
    site_data = site_data[site_data > 0]
    plt.pie(site_data.values, labels=site_data.index, autopct='%1.1f%%', startangle=90)
    plt.title(f'{site} 各项指标占比')
    plt.axis('equal')  # 保证饼图为正圆形
    plt.show()

2. 绘制每个Site的指标柱状图

如果要直观对比每个Site的各项指标数值,柱状图更清晰:

# 整体对比所有Site的指标
df.plot(kind='bar', figsize=(10,6))
plt.title('各Site指标数值对比')
plt.xlabel('Site')
plt.ylabel('数值')
plt.legend(title='指标')
plt.show()

# 单独为每个Site绘制柱状图
for site in df.index:
    plt.figure(figsize=(8,4))
    site_data = df.loc[site]
    plt.bar(site_data.index, site_data.values, color=['blue','green','yellow','red'])
    plt.title(f'{site} 各项指标数值')
    plt.xlabel('指标')
    plt.ylabel('数值')
    plt.show()

二、提取各指标最值对应的Site

直接用idxmax()和idxmin()获取每个指标的最值对应Site:

# 获取各指标最大值对应的Site
max_sites = df.idxmax()
print('各指标最大值对应的Site:')
print(max_sites)

# 获取各指标最小值对应的Site
min_sites = df.idxmin()
print('\n各指标最小值对应的Site:')
print(min_sites)

执行后输出:

各指标最大值对应的Site:
A      Red
B      Red
C    Green
D    Green
dtype: object

各指标最小值对应的Site:
A    Green
B    Yellow
C    Yellow
D      Red
dtype: object

之前尝试代码的问题说明

  • 代码1:df[["C"]].value_counts()是统计C列不同值的出现次数,不是每个Site的C值,所以图表不符合需求;
  • 代码2:df.iloc[1]取的是第二行(Green)的所有数据,x轴和y轴用同一组数据逻辑错误,应该用Site作为x轴、对应指标作为y轴。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 15:30:18